Subversion-Projekte lars-tiefland.laravel_shop

Revision

Zur aktuellen Revision | Details | Letzte Änderung | Log anzeigen | RSS feed

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