Regex.php
2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
namespace Dotenv\Regex;
use PhpOption\Option;
class Regex
{
/**
* Perform a preg replace, wrapping up the result.
*
* @param string $pattern
* @param string $replacement
* @param string $subject
*
* @return \Dotenv\Regex\Result
*/
public static function replace($pattern, $replacement, $subject)
{
return self::pregAndWrap(function ($subject) use ($pattern, $replacement) {
return preg_replace($pattern, $replacement, $subject);
}, $subject);
}
/**
* Perform a preg replace callback, wrapping up the result.
*
* @param string $pattern
* @param callable $callback
* @param string $subject
*
* @return \Dotenv\Regex\Result
*/
public static function replaceCallback($pattern, callable $callback, $subject)
{
return self::pregAndWrap(function ($subject) use ($pattern, $callback) {
return preg_replace_callback($pattern, $callback, $subject);
}, $subject);
}
/**
* Perform a preg operation, wrapping up the result.
*
* @param callable $operation
* @param string $subject
*
* @return \Dotenv\Regex\Result
*/
private static function pregAndWrap(callable $operation, $subject)
{
$result = (string) @$operation($subject);
if (($e = preg_last_error()) !== PREG_NO_ERROR) {
return Error::create(self::lookupError($e));
}
return Success::create($result);
}
/**
* Lookup the preg error code.
*
* @param int $code
*
* @return string
*/
private static function lookupError($code)
{
return Option::fromValue(get_defined_constants(true))
->filter(function (array $consts) {
return isset($consts['pcre']) && defined('ARRAY_FILTER_USE_KEY');
})
->map(function (array $consts) {
return array_filter($consts['pcre'], function ($msg) {
return substr($msg, -6) === '_ERROR';
}, ARRAY_FILTER_USE_KEY);
})
->flatMap(function (array $errors) use ($code) {
return Option::fromValue(
array_search($code, $errors, true)
);
})
->getOrElse('PREG_ERROR');
}
}