-
-
Notifications
You must be signed in to change notification settings - Fork 576
Expand file tree
/
Copy pathUtils.php
More file actions
297 lines (245 loc) · 7.95 KB
/
Copy pathUtils.php
File metadata and controls
297 lines (245 loc) · 7.95 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
<?php declare(strict_types=1);
namespace GraphQL\Utils;
use GraphQL\Error\Error;
use GraphQL\Error\Warning;
use GraphQL\Language\AST\Node;
class Utils
{
public static function undefined(): \stdClass
{
static $undefined;
return $undefined ??= new \stdClass();
}
/** @param array<string, mixed> $vars */
public static function assign(object $obj, array $vars): object
{
foreach ($vars as $key => $value) {
if (! property_exists($obj, $key)) {
$cls = get_class($obj);
Warning::warn(
"Trying to set non-existing property '{$key}' on class '{$cls}'",
Warning::WARNING_ASSIGN
);
}
$obj->{$key} = $value;
}
return $obj;
}
/**
* Print a value that came from JSON for debugging purposes.
*
* @param mixed $value
*/
public static function printSafeJson($value): string
{
if ($value instanceof \stdClass) {
return static::jsonEncodeOrSerialize($value);
}
return static::printSafeInternal($value);
}
/**
* Print a value that came from PHP for debugging purposes.
*
* @param mixed $value
*/
public static function printSafe($value): string
{
if (is_object($value)) {
if (method_exists($value, '__toString')) {
return $value->__toString();
}
return 'instance of ' . get_class($value);
}
return static::printSafeInternal($value);
}
/** @param \stdClass|array<mixed> $value */
protected static function jsonEncodeOrSerialize($value): string
{
try {
return json_encode($value, JSON_THROW_ON_ERROR);
} catch (\JsonException $jsonException) {
return serialize($value);
}
}
/** @param mixed $value */
protected static function printSafeInternal($value): string
{
if (is_array($value)) {
return static::jsonEncodeOrSerialize($value);
}
if ($value === '') {
return '(empty string)';
}
if ($value === null) {
return 'null';
}
if ($value === false) {
return 'false';
}
if ($value === true) {
return 'true';
}
if (is_string($value)) {
return "\"{$value}\"";
}
if (is_scalar($value)) {
return (string) $value;
}
return gettype($value);
}
/** UTF-8 compatible chr(). */
public static function chr(int $ord, string $encoding = 'UTF-8'): string
{
if ($encoding === 'UCS-4BE') {
return pack('N', $ord);
}
$converted = mb_convert_encoding(self::chr($ord, 'UCS-4BE'), $encoding, 'UCS-4BE');
assert(is_string($converted), 'format string is statically known to be correct');
return $converted;
}
/** UTF-8 compatible ord(). */
public static function ord(string $char, string $encoding = 'UTF-8'): int
{
if (! isset($char[1])) {
return ord($char);
}
if ($encoding !== 'UCS-4BE') {
$char = mb_convert_encoding($char, 'UCS-4BE', $encoding);
assert(is_string($char), 'format string is statically known to be correct');
}
$unpacked = unpack('N', $char);
assert(is_array($unpacked), 'format string is statically known to be correct');
return $unpacked[1];
}
/** Returns UTF-8 char code at given $positing of the $string. */
public static function charCodeAt(string $string, int $position): int
{
$char = mb_substr($string, $position, 1, 'UTF-8');
return self::ord($char);
}
/** @throws \JsonException */
public static function printCharCode(?int $code): string
{
if ($code === null) {
return '<EOF>';
}
return $code < 0x007F
// Trust JSON for ASCII
? json_encode(self::chr($code), JSON_THROW_ON_ERROR)
// Otherwise, print the escaped form
: '"\\u' . dechex($code) . '"';
}
/**
* Upholds the spec rules about naming.
*
* @throws Error
*/
public static function assertValidName(string $name): void
{
$error = self::isValidNameError($name);
if ($error !== null) {
throw $error;
}
}
/** Returns an Error if a name is invalid. */
public static function isValidNameError(string $name, ?Node $node = null): ?Error
{
if (isset($name[1]) && $name[0] === '_' && $name[1] === '_') {
return new Error(
"Name \"{$name}\" must not begin with \"__\", which is reserved by GraphQL introspection.",
$node
);
}
if (preg_match('/^[_a-zA-Z][_a-zA-Z0-9]*$/', $name) !== 1) {
return new Error(
"Names must match /^[_a-zA-Z][_a-zA-Z0-9]*\$/ but \"{$name}\" does not.",
$node
);
}
return null;
}
/** @param array<string> $items */
public static function quotedOrList(array $items): string
{
$quoted = array_map(
static fn (string $item): string => "\"{$item}\"",
$items
);
return self::orList($quoted);
}
/** @param array<string> $items */
public static function orList(array $items): string
{
if ($items === []) {
return '';
}
$selected = array_slice($items, 0, 5);
$selectedLength = count($selected);
$firstSelected = $selected[0];
if ($selectedLength === 1) {
return $firstSelected;
}
return array_reduce(
range(1, $selectedLength - 1),
static fn ($list, $index): string => $list
. ($selectedLength > 2 ? ', ' : ' ')
. ($index === $selectedLength - 1 ? 'or ' : '')
. $selected[$index],
$firstSelected
);
}
/**
* Given an invalid input string and a list of valid options, returns a filtered
* list of valid options sorted based on their similarity with the input.
*
* @param array<string> $options
*
* @return array<int, string>
*/
public static function suggestionList(string $input, array $options): array
{
/** @var array<string, int> $optionsByDistance */
$optionsByDistance = [];
$lexicalDistance = new LexicalDistance($input);
$threshold = mb_strlen($input) * 0.4 + 1;
foreach ($options as $option) {
$distance = $lexicalDistance->measure($option, $threshold);
if ($distance !== null) {
$optionsByDistance[$option] = $distance;
}
}
uksort($optionsByDistance, static function (string $a, string $b) use ($optionsByDistance) {
$distanceDiff = $optionsByDistance[$a] - $optionsByDistance[$b];
return $distanceDiff !== 0 ? $distanceDiff : strnatcmp($a, $b);
});
return array_map('strval', array_keys($optionsByDistance));
}
/**
* Try to extract the value for a key from an object like value.
*
* @param mixed $objectLikeValue
*
* @return mixed
*/
public static function extractKey($objectLikeValue, string $key)
{
if (is_array($objectLikeValue) || $objectLikeValue instanceof \ArrayAccess) {
return $objectLikeValue[$key] ?? null;
}
if (is_object($objectLikeValue)) {
return $objectLikeValue->{$key} ?? null;
}
return null;
}
/**
* Split a string that has either Unix, Windows or Mac style newlines into lines.
*
* @return list<string>
*/
public static function splitLines(string $value): array
{
$lines = preg_split("/\r\n|\r|\n/", $value);
assert(is_array($lines), 'given the regex is valid');
return $lines;
}
}