Helpers.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. use Nette;
  9. class Helpers
  10. {
  11. /**
  12. * Executes a callback and returns the captured output as a string.
  13. */
  14. public static function capture(callable $func): string
  15. {
  16. ob_start(function () {});
  17. try {
  18. $func();
  19. return ob_get_clean();
  20. } catch (\Throwable $e) {
  21. ob_end_clean();
  22. throw $e;
  23. }
  24. }
  25. /**
  26. * Returns the last occurred PHP error or an empty string if no error occurred. Unlike error_get_last(),
  27. * it is nit affected by the PHP directive html_errors and always returns text, not HTML.
  28. */
  29. public static function getLastError(): string
  30. {
  31. $message = error_get_last()['message'] ?? '';
  32. $message = ini_get('html_errors') ? Html::htmlToText($message) : $message;
  33. $message = preg_replace('#^\w+\(.*?\): #', '', $message);
  34. return $message;
  35. }
  36. /**
  37. * Converts false to null, does not change other values.
  38. * @param mixed $value
  39. * @return mixed
  40. */
  41. public static function falseToNull($value)
  42. {
  43. return $value === false ? null : $value;
  44. }
  45. /**
  46. * Returns value clamped to the inclusive range of min and max.
  47. * @param int|float $value
  48. * @param int|float $min
  49. * @param int|float $max
  50. * @return int|float
  51. */
  52. public static function clamp($value, $min, $max)
  53. {
  54. if ($min > $max) {
  55. throw new Nette\InvalidArgumentException("Minimum ($min) is not less than maximum ($max).");
  56. }
  57. return min(max($value, $min), $max);
  58. }
  59. /**
  60. * Looks for a string from possibilities that is most similar to value, but not the same (for 8-bit encoding).
  61. * @param string[] $possibilities
  62. */
  63. public static function getSuggestion(array $possibilities, string $value): ?string
  64. {
  65. $best = null;
  66. $min = (strlen($value) / 4 + 1) * 10 + .1;
  67. foreach (array_unique($possibilities) as $item) {
  68. if ($item !== $value && ($len = levenshtein($item, $value, 10, 11, 10)) < $min) {
  69. $min = $len;
  70. $best = $item;
  71. }
  72. }
  73. return $best;
  74. }
  75. }