ErrorHandlerTest.php 26 KB

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