ErrorHandlerTest.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\ErrorHandler\Tests;
  11. use PHPUnit\Framework\TestCase;
  12. use Psr\Log\LoggerInterface;
  13. use Psr\Log\LogLevel;
  14. use Psr\Log\NullLogger;
  15. use Symfony\Component\ErrorHandler\BufferingLogger;
  16. use Symfony\Component\ErrorHandler\Error\ClassNotFoundError;
  17. use Symfony\Component\ErrorHandler\Error\FatalError;
  18. use Symfony\Component\ErrorHandler\ErrorHandler;
  19. use Symfony\Component\ErrorHandler\Exception\SilencedErrorContext;
  20. use Symfony\Component\ErrorHandler\Tests\Fixtures\ErrorHandlerThatUsesThePreviousOne;
  21. use Symfony\Component\ErrorHandler\Tests\Fixtures\LoggerThatSetAnErrorHandler;
  22. /**
  23. * ErrorHandlerTest.
  24. *
  25. * @author Robert Schönthal <seroscho@googlemail.com>
  26. * @author Nicolas Grekas <p@tchwork.com>
  27. */
  28. class ErrorHandlerTest extends TestCase
  29. {
  30. protected function tearDown(): void
  31. {
  32. $r = new \ReflectionProperty(ErrorHandler::class, 'exitCode');
  33. $r->setAccessible(true);
  34. $r->setValue(null, 0);
  35. }
  36. public function testRegister()
  37. {
  38. $handler = ErrorHandler::register();
  39. try {
  40. $this->assertInstanceOf(ErrorHandler::class, $handler);
  41. $this->assertSame($handler, ErrorHandler::register());
  42. $newHandler = new ErrorHandler();
  43. $this->assertSame($handler, ErrorHandler::register($newHandler, false));
  44. $h = set_error_handler('var_dump');
  45. restore_error_handler();
  46. $this->assertSame([$handler, 'handleError'], $h);
  47. try {
  48. $this->assertSame($newHandler, ErrorHandler::register($newHandler, true));
  49. $h = set_error_handler('var_dump');
  50. restore_error_handler();
  51. $this->assertSame([$newHandler, 'handleError'], $h);
  52. } finally {
  53. restore_error_handler();
  54. restore_exception_handler();
  55. }
  56. } finally {
  57. restore_error_handler();
  58. restore_exception_handler();
  59. }
  60. }
  61. public function testErrorGetLast()
  62. {
  63. $logger = $this->createMock(LoggerInterface::class);
  64. $handler = ErrorHandler::register();
  65. $handler->setDefaultLogger($logger);
  66. $handler->screamAt(\E_ALL);
  67. try {
  68. @trigger_error('Hello', \E_USER_WARNING);
  69. $expected = [
  70. 'type' => \E_USER_WARNING,
  71. 'message' => 'Hello',
  72. 'file' => __FILE__,
  73. 'line' => __LINE__ - 5,
  74. ];
  75. $this->assertSame($expected, error_get_last());
  76. } finally {
  77. restore_error_handler();
  78. restore_exception_handler();
  79. }
  80. }
  81. public function testNotice()
  82. {
  83. ErrorHandler::register();
  84. try {
  85. self::triggerNotice($this);
  86. $this->fail('ErrorException expected');
  87. } catch (\ErrorException $exception) {
  88. // if an exception is thrown, the test passed
  89. if (\PHP_VERSION_ID < 80000) {
  90. $this->assertEquals(\E_NOTICE, $exception->getSeverity());
  91. $this->assertMatchesRegularExpression('/^Notice: Undefined variable: (foo|bar)/', $exception->getMessage());
  92. } else {
  93. $this->assertEquals(\E_WARNING, $exception->getSeverity());
  94. $this->assertMatchesRegularExpression('/^Warning: Undefined variable \$(foo|bar)/', $exception->getMessage());
  95. }
  96. $this->assertEquals(__FILE__, $exception->getFile());
  97. $trace = $exception->getTrace();
  98. $this->assertEquals(__FILE__, $trace[0]['file']);
  99. $this->assertEquals(__CLASS__, $trace[0]['class']);
  100. $this->assertEquals('triggerNotice', $trace[0]['function']);
  101. $this->assertEquals('::', $trace[0]['type']);
  102. $this->assertEquals(__FILE__, $trace[0]['file']);
  103. $this->assertEquals(__CLASS__, $trace[1]['class']);
  104. $this->assertEquals(__FUNCTION__, $trace[1]['function']);
  105. $this->assertEquals('->', $trace[1]['type']);
  106. } finally {
  107. restore_error_handler();
  108. restore_exception_handler();
  109. }
  110. }
  111. // dummy function to test trace in error handler.
  112. public static function triggerNotice($that)
  113. {
  114. $that->assertSame('', $foo.$foo.$bar);
  115. }
  116. public function testFailureCall()
  117. {
  118. $this->expectException(\ErrorException::class);
  119. $this->expectExceptionMessageMatches('/^fopen\(unknown\.txt\): [Ff]ailed to open stream: No such file or directory$/');
  120. ErrorHandler::call('fopen', 'unknown.txt', 'r');
  121. }
  122. public function testCallRestoreErrorHandler()
  123. {
  124. $prev = set_error_handler('var_dump');
  125. try {
  126. ErrorHandler::call('fopen', 'unknown.txt', 'r');
  127. $this->fail('An \ErrorException should have been raised');
  128. } catch (\ErrorException $e) {
  129. $prev = set_error_handler($prev);
  130. restore_error_handler();
  131. } finally {
  132. restore_error_handler();
  133. }
  134. $this->assertSame('var_dump', $prev);
  135. }
  136. public function testCallErrorExceptionInfo()
  137. {
  138. try {
  139. ErrorHandler::call([self::class, 'triggerNotice'], $this);
  140. $this->fail('An \ErrorException should have been raised');
  141. } catch (\ErrorException $e) {
  142. $trace = $e->getTrace();
  143. if (\PHP_VERSION_ID < 80000) {
  144. $this->assertEquals(\E_NOTICE, $e->getSeverity());
  145. $this->assertSame('Undefined variable: foo', $e->getMessage());
  146. } else {
  147. $this->assertEquals(\E_WARNING, $e->getSeverity());
  148. $this->assertSame('Undefined variable $foo', $e->getMessage());
  149. }
  150. $this->assertSame(__FILE__, $e->getFile());
  151. $this->assertSame(0, $e->getCode());
  152. $this->assertStringMatchesFormat('%A{closure%A}', $trace[0]['function']);
  153. $this->assertSame(ErrorHandler::class, $trace[0]['class']);
  154. $this->assertSame('triggerNotice', $trace[1]['function']);
  155. $this->assertSame(__CLASS__, $trace[1]['class']);
  156. }
  157. }
  158. public function testSuccessCall()
  159. {
  160. touch($filename = tempnam(sys_get_temp_dir(), 'sf_error_handler_'));
  161. self::assertIsResource(ErrorHandler::call('fopen', $filename, 'r'));
  162. unlink($filename);
  163. }
  164. public function testConstruct()
  165. {
  166. try {
  167. $handler = ErrorHandler::register();
  168. $handler->throwAt(3, true);
  169. $this->assertEquals(3 | \E_RECOVERABLE_ERROR | \E_USER_ERROR, $handler->throwAt(0));
  170. } finally {
  171. restore_error_handler();
  172. restore_exception_handler();
  173. }
  174. }
  175. public function testDefaultLogger()
  176. {
  177. try {
  178. $logger = $this->createMock(LoggerInterface::class);
  179. $handler = ErrorHandler::register();
  180. $handler->setDefaultLogger($logger, \E_NOTICE);
  181. $handler->setDefaultLogger($logger, [\E_USER_NOTICE => LogLevel::CRITICAL]);
  182. $loggers = [
  183. \E_DEPRECATED => [null, LogLevel::INFO],
  184. \E_USER_DEPRECATED => [null, LogLevel::INFO],
  185. \E_NOTICE => [$logger, LogLevel::WARNING],
  186. \E_USER_NOTICE => [$logger, LogLevel::CRITICAL],
  187. \E_WARNING => [null, LogLevel::WARNING],
  188. \E_USER_WARNING => [null, LogLevel::WARNING],
  189. \E_COMPILE_WARNING => [null, LogLevel::WARNING],
  190. \E_CORE_WARNING => [null, LogLevel::WARNING],
  191. \E_USER_ERROR => [null, LogLevel::CRITICAL],
  192. \E_RECOVERABLE_ERROR => [null, LogLevel::CRITICAL],
  193. \E_COMPILE_ERROR => [null, LogLevel::CRITICAL],
  194. \E_PARSE => [null, LogLevel::CRITICAL],
  195. \E_ERROR => [null, LogLevel::CRITICAL],
  196. \E_CORE_ERROR => [null, LogLevel::CRITICAL],
  197. ];
  198. if (\PHP_VERSION_ID < 80400) {
  199. $loggers[\E_STRICT] = [null, LogLevel::WARNING];
  200. }
  201. $this->assertSame($loggers, $handler->setLoggers([]));
  202. } finally {
  203. restore_error_handler();
  204. restore_exception_handler();
  205. }
  206. }
  207. public function testHandleError()
  208. {
  209. try {
  210. $handler = ErrorHandler::register();
  211. $handler->throwAt(0, true);
  212. $this->assertFalse($handler->handleError(0, 'foo', 'foo.php', 12, []));
  213. restore_error_handler();
  214. restore_exception_handler();
  215. $handler = ErrorHandler::register();
  216. $handler->throwAt(3, true);
  217. $this->assertFalse($handler->handleError(4, 'foo', 'foo.php', 12, []));
  218. restore_error_handler();
  219. restore_exception_handler();
  220. $handler = ErrorHandler::register();
  221. $handler->throwAt(3, true);
  222. try {
  223. $handler->handleError(4, 'foo', 'foo.php', 12, []);
  224. } catch (\ErrorException $e) {
  225. $this->assertSame('Parse Error: foo', $e->getMessage());
  226. $this->assertSame(4, $e->getSeverity());
  227. $this->assertSame('foo.php', $e->getFile());
  228. $this->assertSame(12, $e->getLine());
  229. }
  230. restore_error_handler();
  231. restore_exception_handler();
  232. $handler = ErrorHandler::register();
  233. $handler->throwAt(\E_USER_DEPRECATED, true);
  234. $this->assertFalse($handler->handleError(\E_USER_DEPRECATED, 'foo', 'foo.php', 12, []));
  235. restore_error_handler();
  236. restore_exception_handler();
  237. $handler = ErrorHandler::register();
  238. $handler->throwAt(\E_DEPRECATED, true);
  239. $this->assertFalse($handler->handleError(\E_DEPRECATED, 'foo', 'foo.php', 12, []));
  240. restore_error_handler();
  241. restore_exception_handler();
  242. $logger = $this->createMock(LoggerInterface::class);
  243. $warnArgCheck = function ($logLevel, $message, $context) {
  244. $this->assertEquals('info', $logLevel);
  245. $this->assertEquals('User Deprecated: foo', $message);
  246. $this->assertArrayHasKey('exception', $context);
  247. $exception = $context['exception'];
  248. $this->assertInstanceOf(\ErrorException::class, $exception);
  249. $this->assertSame('User Deprecated: foo', $exception->getMessage());
  250. $this->assertSame(\E_USER_DEPRECATED, $exception->getSeverity());
  251. };
  252. $logger
  253. ->expects($this->once())
  254. ->method('log')
  255. ->willReturnCallback($warnArgCheck)
  256. ;
  257. $handler = ErrorHandler::register();
  258. $handler->setDefaultLogger($logger, \E_USER_DEPRECATED);
  259. $this->assertTrue($handler->handleError(\E_USER_DEPRECATED, 'foo', 'foo.php', 12, []));
  260. restore_error_handler();
  261. restore_exception_handler();
  262. $logger = $this->createMock(LoggerInterface::class);
  263. $line = null;
  264. $logArgCheck = function ($level, $message, $context) use (&$line) {
  265. $this->assertArrayHasKey('exception', $context);
  266. $exception = $context['exception'];
  267. if (\PHP_VERSION_ID < 80000) {
  268. $this->assertEquals('Notice: Undefined variable: undefVar', $message);
  269. $this->assertSame(\E_NOTICE, $exception->getSeverity());
  270. } else {
  271. $this->assertEquals('Warning: Undefined variable $undefVar', $message);
  272. $this->assertSame(\E_WARNING, $exception->getSeverity());
  273. }
  274. $this->assertInstanceOf(SilencedErrorContext::class, $exception);
  275. $this->assertSame(__FILE__, $exception->getFile());
  276. $this->assertSame($line, $exception->getLine());
  277. $this->assertNotEmpty($exception->getTrace());
  278. $this->assertSame(1, $exception->count);
  279. };
  280. $logger
  281. ->expects($this->once())
  282. ->method('log')
  283. ->willReturnCallback($logArgCheck)
  284. ;
  285. $handler = ErrorHandler::register();
  286. if (\PHP_VERSION_ID < 80000) {
  287. $handler->setDefaultLogger($logger, \E_NOTICE);
  288. $handler->screamAt(\E_NOTICE);
  289. } else {
  290. $handler->setDefaultLogger($logger, \E_WARNING);
  291. $handler->screamAt(\E_WARNING);
  292. }
  293. unset($undefVar);
  294. $line = __LINE__ + 1;
  295. @$undefVar++;
  296. } finally {
  297. restore_error_handler();
  298. restore_exception_handler();
  299. }
  300. }
  301. public function testHandleUserError()
  302. {
  303. if (\PHP_VERSION_ID >= 70400) {
  304. $this->markTestSkipped('PHP 7.4 allows __toString to throw exceptions');
  305. }
  306. try {
  307. $handler = ErrorHandler::register();
  308. $handler->throwAt(0, true);
  309. $e = null;
  310. $x = new \Exception('Foo');
  311. try {
  312. $f = new Fixtures\ToStringThrower($x);
  313. $f .= ''; // Trigger $f->__toString()
  314. } catch (\Exception $e) {
  315. }
  316. $this->assertSame($x, $e);
  317. } finally {
  318. restore_error_handler();
  319. restore_exception_handler();
  320. }
  321. }
  322. public function testHandleErrorWithAnonymousClass()
  323. {
  324. $anonymousObject = new class() extends \stdClass {
  325. };
  326. $handler = ErrorHandler::register();
  327. try {
  328. trigger_error('foo '.\get_class($anonymousObject).' bar', \E_USER_WARNING);
  329. $this->fail('Exception expected.');
  330. } catch (\ErrorException $e) {
  331. } finally {
  332. restore_error_handler();
  333. restore_exception_handler();
  334. }
  335. $this->assertSame('User Warning: foo stdClass@anonymous bar', $e->getMessage());
  336. }
  337. public function testHandleDeprecation()
  338. {
  339. $logArgCheck = function ($level, $message, $context) {
  340. $this->assertEquals(LogLevel::INFO, $level);
  341. $this->assertArrayHasKey('exception', $context);
  342. $exception = $context['exception'];
  343. $this->assertInstanceOf(\ErrorException::class, $exception);
  344. $this->assertSame('User Deprecated: Foo deprecation', $exception->getMessage());
  345. };
  346. $logger = $this->createMock(LoggerInterface::class);
  347. $logger
  348. ->expects($this->once())
  349. ->method('log')
  350. ->willReturnCallback($logArgCheck)
  351. ;
  352. $handler = new ErrorHandler();
  353. $handler->setDefaultLogger($logger);
  354. @$handler->handleError(\E_USER_DEPRECATED, 'Foo deprecation', __FILE__, __LINE__, []);
  355. }
  356. /**
  357. * @dataProvider handleExceptionProvider
  358. */
  359. public function testHandleException(string $expectedMessage, \Throwable $exception)
  360. {
  361. try {
  362. $logger = $this->createMock(LoggerInterface::class);
  363. $handler = ErrorHandler::register();
  364. $logArgCheck = function ($level, $message, $context) use ($expectedMessage, $exception) {
  365. $this->assertSame($expectedMessage, $message);
  366. $this->assertArrayHasKey('exception', $context);
  367. $this->assertInstanceOf(\get_class($exception), $context['exception']);
  368. };
  369. $logger
  370. ->expects($this->exactly(2))
  371. ->method('log')
  372. ->willReturnCallback($logArgCheck)
  373. ;
  374. $handler->setDefaultLogger($logger, \E_ERROR);
  375. $handler->setExceptionHandler(null);
  376. try {
  377. $handler->handleException($exception);
  378. $this->fail('Exception expected');
  379. } catch (\Throwable $e) {
  380. $this->assertSame($exception, $e);
  381. }
  382. $handler->setExceptionHandler(function ($e) use ($exception) {
  383. $this->assertSame($exception, $e);
  384. });
  385. $handler->handleException($exception);
  386. } finally {
  387. restore_error_handler();
  388. restore_exception_handler();
  389. }
  390. }
  391. public static function handleExceptionProvider(): array
  392. {
  393. return [
  394. ['Uncaught Exception: foo', new \Exception('foo')],
  395. ['Uncaught Exception: foo', new class('foo') extends \RuntimeException {
  396. }],
  397. ['Uncaught Exception: foo stdClass@anonymous bar', new \RuntimeException('foo '.\get_class(new class() extends \stdClass {
  398. }).' bar')],
  399. ['Uncaught Error: bar', new \Error('bar')],
  400. ['Uncaught ccc', new \ErrorException('ccc')],
  401. ];
  402. }
  403. public function testBootstrappingLogger()
  404. {
  405. $bootLogger = new BufferingLogger();
  406. $handler = new ErrorHandler($bootLogger);
  407. $loggers = [
  408. \E_DEPRECATED => [$bootLogger, LogLevel::INFO],
  409. \E_USER_DEPRECATED => [$bootLogger, LogLevel::INFO],
  410. \E_NOTICE => [$bootLogger, LogLevel::WARNING],
  411. \E_USER_NOTICE => [$bootLogger, LogLevel::WARNING],
  412. \E_WARNING => [$bootLogger, LogLevel::WARNING],
  413. \E_USER_WARNING => [$bootLogger, LogLevel::WARNING],
  414. \E_COMPILE_WARNING => [$bootLogger, LogLevel::WARNING],
  415. \E_CORE_WARNING => [$bootLogger, LogLevel::WARNING],
  416. \E_USER_ERROR => [$bootLogger, LogLevel::CRITICAL],
  417. \E_RECOVERABLE_ERROR => [$bootLogger, LogLevel::CRITICAL],
  418. \E_COMPILE_ERROR => [$bootLogger, LogLevel::CRITICAL],
  419. \E_PARSE => [$bootLogger, LogLevel::CRITICAL],
  420. \E_ERROR => [$bootLogger, LogLevel::CRITICAL],
  421. \E_CORE_ERROR => [$bootLogger, LogLevel::CRITICAL],
  422. ];
  423. if (\PHP_VERSION_ID < 80400) {
  424. $loggers[\E_STRICT] = [$bootLogger, LogLevel::WARNING];
  425. }
  426. $this->assertSame($loggers, $handler->setLoggers([]));
  427. $handler->handleError(\E_DEPRECATED, 'Foo message', __FILE__, 123, []);
  428. $logs = $bootLogger->cleanLogs();
  429. $this->assertCount(1, $logs);
  430. $log = $logs[0];
  431. $this->assertSame('info', $log[0]);
  432. $this->assertSame('Deprecated: Foo message', $log[1]);
  433. $this->assertArrayHasKey('exception', $log[2]);
  434. $exception = $log[2]['exception'];
  435. $this->assertInstanceOf(\ErrorException::class, $exception);
  436. $this->assertSame('Deprecated: Foo message', $exception->getMessage());
  437. $this->assertSame(__FILE__, $exception->getFile());
  438. $this->assertSame(123, $exception->getLine());
  439. $this->assertSame(\E_DEPRECATED, $exception->getSeverity());
  440. $bootLogger->log(LogLevel::WARNING, 'Foo message', ['exception' => $exception]);
  441. $mockLogger = $this->createMock(LoggerInterface::class);
  442. $mockLogger->expects($this->once())
  443. ->method('log')
  444. ->with(LogLevel::WARNING, 'Foo message', ['exception' => $exception]);
  445. $handler->setLoggers([\E_DEPRECATED => [$mockLogger, LogLevel::WARNING]]);
  446. }
  447. public function testSettingLoggerWhenExceptionIsBuffered()
  448. {
  449. $bootLogger = new BufferingLogger();
  450. $handler = new ErrorHandler($bootLogger);
  451. $exception = new \Exception('Foo message');
  452. $mockLogger = $this->createMock(LoggerInterface::class);
  453. $mockLogger->expects($this->once())
  454. ->method('log')
  455. ->with(LogLevel::CRITICAL, 'Uncaught Exception: Foo message', ['exception' => $exception]);
  456. $handler->setExceptionHandler(function () use ($handler, $mockLogger) {
  457. $handler->setDefaultLogger($mockLogger);
  458. });
  459. $handler->handleException($exception);
  460. }
  461. public function testHandleFatalError()
  462. {
  463. try {
  464. $logger = $this->createMock(LoggerInterface::class);
  465. $handler = ErrorHandler::register();
  466. $error = [
  467. 'type' => \E_PARSE,
  468. 'message' => 'foo',
  469. 'file' => 'bar',
  470. 'line' => 123,
  471. ];
  472. $logArgCheck = function ($level, $message, $context) {
  473. $this->assertEquals('Fatal Parse Error: foo', $message);
  474. $this->assertArrayHasKey('exception', $context);
  475. $this->assertInstanceOf(FatalError::class, $context['exception']);
  476. };
  477. $logger
  478. ->expects($this->once())
  479. ->method('log')
  480. ->willReturnCallback($logArgCheck)
  481. ;
  482. $handler->setDefaultLogger($logger, \E_PARSE);
  483. $handler->setExceptionHandler(null);
  484. $handler->handleFatalError($error);
  485. } finally {
  486. restore_error_handler();
  487. restore_exception_handler();
  488. }
  489. }
  490. public function testHandleErrorException()
  491. {
  492. $exception = new \Error("Class 'IReallyReallyDoNotExistAnywhereInTheRepositoryISwear' not found");
  493. $handler = new ErrorHandler();
  494. $handler->setExceptionHandler(function () use (&$args) {
  495. $args = \func_get_args();
  496. });
  497. $handler->handleException($exception);
  498. $this->assertInstanceOf(ClassNotFoundError::class, $args[0]);
  499. $this->assertStringStartsWith("Attempted to load class \"IReallyReallyDoNotExistAnywhereInTheRepositoryISwear\" from the global namespace.\nDid you forget a \"use\" statement", $args[0]->getMessage());
  500. }
  501. public function testCustomExceptionHandler()
  502. {
  503. $this->expectException(\Exception::class);
  504. $handler = new ErrorHandler();
  505. $handler->setExceptionHandler(function ($e) use ($handler) {
  506. $handler->setExceptionHandler(null);
  507. $handler->handleException($e);
  508. });
  509. $handler->handleException(new \Exception());
  510. }
  511. public function testRenderException()
  512. {
  513. $handler = new ErrorHandler();
  514. $handler->setExceptionHandler([$handler, 'renderException']);
  515. ob_start();
  516. $handler->handleException(new \RuntimeException('Class Foo not found'));
  517. $response = ob_get_clean();
  518. self::assertStringContainsString('Class Foo not found', $response);
  519. }
  520. /**
  521. * @dataProvider errorHandlerWhenLoggingProvider
  522. */
  523. public function testErrorHandlerWhenLogging(bool $previousHandlerWasDefined, bool $loggerSetsAnotherHandler, bool $nextHandlerIsDefined)
  524. {
  525. try {
  526. if ($previousHandlerWasDefined) {
  527. set_error_handler('count');
  528. }
  529. $logger = $loggerSetsAnotherHandler ? new LoggerThatSetAnErrorHandler() : new NullLogger();
  530. $handler = ErrorHandler::register();
  531. $handler->setDefaultLogger($logger);
  532. if ($nextHandlerIsDefined) {
  533. $handler = ErrorHandlerThatUsesThePreviousOne::register();
  534. }
  535. @trigger_error('foo', \E_USER_DEPRECATED);
  536. @trigger_error('bar', \E_USER_DEPRECATED);
  537. $this->assertSame([$handler, 'handleError'], set_error_handler('var_dump'));
  538. if ($logger instanceof LoggerThatSetAnErrorHandler) {
  539. $this->assertCount(2, $logger->cleanLogs());
  540. }
  541. restore_error_handler();
  542. if ($previousHandlerWasDefined) {
  543. restore_error_handler();
  544. }
  545. if ($nextHandlerIsDefined) {
  546. restore_error_handler();
  547. }
  548. } finally {
  549. restore_error_handler();
  550. restore_exception_handler();
  551. }
  552. }
  553. public static function errorHandlerWhenLoggingProvider(): iterable
  554. {
  555. foreach ([false, true] as $previousHandlerWasDefined) {
  556. foreach ([false, true] as $loggerSetsAnotherHandler) {
  557. foreach ([false, true] as $nextHandlerIsDefined) {
  558. yield [$previousHandlerWasDefined, $loggerSetsAnotherHandler, $nextHandlerIsDefined];
  559. }
  560. }
  561. }
  562. }
  563. public function testAssertQuietEval()
  564. {
  565. if ('-1' === \ini_get('zend.assertions')) {
  566. $this->markTestSkipped('zend.assertions is forcibly disabled');
  567. }
  568. set_error_handler(function () {});
  569. $ini = [
  570. ini_set('zend.assertions', 1),
  571. ini_set('assert.active', 1),
  572. ini_set('assert.bail', 0),
  573. ini_set('assert.warning', 1),
  574. ini_set('assert.callback', null),
  575. ini_set('assert.exception', 0),
  576. ];
  577. restore_error_handler();
  578. $logger = new BufferingLogger();
  579. $handler = new ErrorHandler($logger);
  580. $handler = ErrorHandler::register($handler);
  581. try {
  582. \assert(false);
  583. } finally {
  584. restore_error_handler();
  585. restore_exception_handler();
  586. ini_set('zend.assertions', $ini[0]);
  587. ini_set('assert.active', $ini[1]);
  588. ini_set('assert.bail', $ini[2]);
  589. ini_set('assert.warning', $ini[3]);
  590. ini_set('assert.callback', $ini[4]);
  591. ini_set('assert.exception', $ini[5]);
  592. }
  593. $logs = $logger->cleanLogs();
  594. $this->assertSame('warning', $logs[0][0]);
  595. $this->assertSame('Warning: assert(): assert(false) failed', $logs[0][1]);
  596. }
  597. public function testHandleTriggerDeprecation()
  598. {
  599. try {
  600. $handler = ErrorHandler::register();
  601. $handler->setDefaultLogger($logger = new BufferingLogger());
  602. $expectedLine = __LINE__ + 1;
  603. trigger_deprecation('foo', '1.2.3', 'bar');
  604. /** @var \ErrorException $exception */
  605. $exception = $logger->cleanLogs()[0][2]['exception'];
  606. $this->assertSame($expectedLine, $exception->getLine());
  607. $this->assertSame(__FILE__, $exception->getFile());
  608. $frame = $exception->getTrace()[0];
  609. $this->assertSame(__CLASS__, $frame['class']);
  610. $this->assertSame(__FUNCTION__, $frame['function']);
  611. $this->assertSame('->', $frame['type']);
  612. } finally {
  613. restore_error_handler();
  614. restore_exception_handler();
  615. }
  616. }
  617. }