Callback.invokeSafe.phpt 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * Test: Nette\Utils\Callback::invokeSafe()
  4. */
  5. declare(strict_types=1);
  6. use Nette\Utils\Callback;
  7. use Tester\Assert;
  8. require __DIR__ . '/../bootstrap.php';
  9. set_error_handler(function ($severity, $message) use (&$res) {
  10. $res = $message;
  11. });
  12. // no error
  13. Callback::invokeSafe('trim', [''], function () {});
  14. trigger_error('OK1', E_USER_WARNING);
  15. Assert::same('OK1', $res);
  16. // skipped error
  17. Callback::invokeSafe('preg_match', ['ab', 'foo'], function () {});
  18. Assert::same('OK1', $res);
  19. // ignored error
  20. Callback::invokeSafe('preg_match', ['ab', 'foo'], fn() => false);
  21. Assert::match('preg_match(): Delimiter must not be alphanumeric%a%', $res);
  22. // error -> exception
  23. Assert::exception(
  24. fn() => Callback::invokeSafe('preg_match', ['ab', 'foo'], function ($message, $severity) {
  25. throw new Exception($message, $severity);
  26. }),
  27. 'Exception',
  28. 'Delimiter must not be alphanumeric%a%',
  29. E_WARNING,
  30. );
  31. trigger_error('OK2', E_USER_WARNING);
  32. Assert::same('OK2', $res);
  33. // error inside
  34. Callback::invokeSafe('preg_replace_callback', ['#.#', function () {
  35. $a++;
  36. }, 'x'], function () {
  37. throw new Exception('Should not be thrown');
  38. });
  39. Assert::same(PHP_VERSION_ID < 80000 ? 'Undefined variable: a' : 'Undefined variable $a', $res);
  40. // exception inside
  41. Assert::exception(
  42. fn() => Callback::invokeSafe('preg_replace_callback', ['#.#', function () {
  43. throw new Exception('in callback');
  44. }, 'x'], function () {}),
  45. 'Exception',
  46. 'in callback',
  47. );
  48. trigger_error('OK3', E_USER_WARNING);
  49. Assert::same('OK3', $res);