Helpers.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * This file is part of the Nette Framework (https://nette.org)
  4. * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
  5. */
  6. declare(strict_types=1);
  7. namespace Nette\Utils;
  8. class Helpers
  9. {
  10. /**
  11. * Executes a callback and returns the captured output as a string.
  12. */
  13. public static function capture(callable $func): string
  14. {
  15. ob_start(function () {});
  16. try {
  17. $func();
  18. return ob_get_clean();
  19. } catch (\Throwable $e) {
  20. ob_end_clean();
  21. throw $e;
  22. }
  23. }
  24. /**
  25. * Returns the last occurred PHP error or an empty string if no error occurred. Unlike error_get_last(),
  26. * it is nit affected by the PHP directive html_errors and always returns text, not HTML.
  27. */
  28. public static function getLastError(): string
  29. {
  30. $message = error_get_last()['message'] ?? '';
  31. $message = ini_get('html_errors') ? Html::htmlToText($message) : $message;
  32. $message = preg_replace('#^\w+\(.*?\): #', '', $message);
  33. return $message;
  34. }
  35. /**
  36. * Converts false to null, does not change other values.
  37. * @param mixed $value
  38. * @return mixed
  39. */
  40. public static function falseToNull($value)
  41. {
  42. return $value === false ? null : $value;
  43. }
  44. /**
  45. * Looks for a string from possibilities that is most similar to value, but not the same (for 8-bit encoding).
  46. * @param string[] $possibilities
  47. */
  48. public static function getSuggestion(array $possibilities, string $value): ?string
  49. {
  50. $best = null;
  51. $min = (strlen($value) / 4 + 1) * 10 + .1;
  52. foreach (array_unique($possibilities) as $item) {
  53. if ($item !== $value && ($len = levenshtein($item, $value, 10, 11, 10)) < $min) {
  54. $min = $len;
  55. $best = $item;
  56. }
  57. }
  58. return $best;
  59. }
  60. }