| 1: | <?php |
| 2: | |
| 3: | declare(strict_types=1); |
| 4: | |
| 5: | /** |
| 6: | * This file is part of the Nexus framework. |
| 7: | * |
| 8: | * (c) John Paul E. Balandan, CPA <paulbalandan@gmail.com> |
| 9: | * |
| 10: | * For the full copyright and license information, please view |
| 11: | * the LICENSE file that was distributed with this source code. |
| 12: | */ |
| 13: | |
| 14: | namespace Nexus\Suppression; |
| 15: | |
| 16: | final class Silencer |
| 17: | { |
| 18: | /** |
| 19: | * @template T |
| 20: | * |
| 21: | * @param (\Closure(): T) $func |
| 22: | * |
| 23: | * @return array{T, null|string} |
| 24: | */ |
| 25: | public static function box(\Closure $func): array |
| 26: | { |
| 27: | $message = null; |
| 28: | |
| 29: | set_error_handler(static function (int $errno, string $errstr) use (&$message): bool { |
| 30: | $message = $errstr; |
| 31: | |
| 32: | if (str_contains($message, '): ')) { |
| 33: | $message = substr($message, (int) strpos($message, '): ') + 3); |
| 34: | } |
| 35: | |
| 36: | return true; |
| 37: | }); |
| 38: | |
| 39: | try { |
| 40: | return [$func(), $message]; |
| 41: | } finally { |
| 42: | restore_error_handler(); |
| 43: | } |
| 44: | } |
| 45: | |
| 46: | /** |
| 47: | * @template T |
| 48: | * |
| 49: | * @param (\Closure(): T) $func |
| 50: | * |
| 51: | * @return T |
| 52: | */ |
| 53: | public static function suppress(\Closure $func): mixed |
| 54: | { |
| 55: | $prevErrorLevel = error_reporting(0); |
| 56: | |
| 57: | try { |
| 58: | return $func(); |
| 59: | } finally { |
| 60: | error_reporting($prevErrorLevel); |
| 61: | } |
| 62: | } |
| 63: | } |
| 64: |