-
Notifications
You must be signed in to change notification settings - Fork 430
/
FilterFunctionReturnTypeHelper.php
380 lines (312 loc) · 12 KB
/
FilterFunctionReturnTypeHelper.php
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
<?php declare(strict_types = 1);
namespace PHPStan\Type\Php;
use PhpParser\Node;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\ShouldNotHappenException;
use PHPStan\TrinaryLogic;
use PHPStan\Type\Accessory\AccessoryNonEmptyStringType;
use PHPStan\Type\Accessory\AccessoryNonFalsyStringType;
use PHPStan\Type\ArrayType;
use PHPStan\Type\BooleanType;
use PHPStan\Type\Constant\ConstantBooleanType;
use PHPStan\Type\Constant\ConstantFloatType;
use PHPStan\Type\Constant\ConstantIntegerType;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\ConstantScalarType;
use PHPStan\Type\FloatType;
use PHPStan\Type\IntegerRangeType;
use PHPStan\Type\IntegerType;
use PHPStan\Type\MixedType;
use PHPStan\Type\NullType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use function array_key_exists;
use function array_merge;
use function hexdec;
use function is_int;
use function octdec;
use function preg_match;
use function sprintf;
use const PHP_FLOAT_EPSILON;
final class FilterFunctionReturnTypeHelper
{
/** All validation filters match 0x100. */
private const VALIDATION_FILTER_BITMASK = 0x100;
private ConstantStringType $flagsString;
/** @var array<int, Type>|null */
private ?array $filterTypeMap = null;
/** @var array<int, list<string>>|null */
private ?array $filterTypeOptions = null;
public function __construct(private ReflectionProvider $reflectionProvider)
{
$this->flagsString = new ConstantStringType('flags');
}
public function getArrayOffsetValueType(Type $arrayType, Type $offsetType, ?Type $filterType, ?Type $flagsType): ?Type
{
$inexistentOffsetType = $this->hasFlag($this->getConstant('FILTER_NULL_ON_FAILURE'), $flagsType)
? new ConstantBooleanType(false)
: new NullType();
$arrayTypeHasOffsetValueType = $arrayType->hasOffsetValueType($offsetType);
if ($arrayTypeHasOffsetValueType->no()) {
return $inexistentOffsetType;
}
$filteredType = $this->getType($arrayType->getOffsetValueType($offsetType), $filterType, $flagsType);
return $arrayTypeHasOffsetValueType->maybe()
? TypeCombinator::union($filteredType, $inexistentOffsetType)
: $filteredType;
}
public function getType(Type $inputType, ?Type $filterType, ?Type $flagsType): Type
{
$mixedType = new MixedType();
if ($filterType === null) {
$filterValue = $this->getConstant('FILTER_DEFAULT');
} else {
if (!$filterType instanceof ConstantIntegerType) {
return $mixedType;
}
$filterValue = $filterType->getValue();
}
if ($flagsType === null) {
$flagsType = new ConstantIntegerType(0);
}
$hasOptions = $this->hasOptions($flagsType);
$options = $hasOptions->yes() ? $this->getOptions($flagsType, $filterValue) : [];
$defaultType = $options['default'] ?? ($this->hasFlag($this->getConstant('FILTER_NULL_ON_FAILURE'), $flagsType)
? new NullType()
: new ConstantBooleanType(false));
if ($inputType->isScalar()->no() && $inputType->isNull()->no()) {
return $defaultType;
}
$exactType = $this->determineExactType($inputType, $filterValue, $defaultType, $flagsType);
$type = $exactType ?? $this->getFilterTypeMap()[$filterValue] ?? $mixedType;
$type = $this->applyRangeOptions($type, $options, $defaultType);
if ($inputType->isNonEmptyString()->yes()
&& $type->isString()->yes()
&& !$this->canStringBeSanitized($filterValue, $flagsType)) {
$accessory = new AccessoryNonEmptyStringType();
if ($inputType->isNonFalsyString()->yes()) {
$accessory = new AccessoryNonFalsyStringType();
}
$type = TypeCombinator::intersect($type, $accessory);
}
if ($exactType === null || $hasOptions->maybe() || (!$inputType->equals($type) && $inputType->isSuperTypeOf($type)->yes())) {
if ($defaultType->isSuperTypeOf($type)->no()) {
$type = TypeCombinator::union($type, $defaultType);
}
}
if ($this->hasFlag($this->getConstant('FILTER_FORCE_ARRAY'), $flagsType)) {
return new ArrayType(new MixedType(), $type);
}
return $type;
}
/**
* @return array<int, Type>
*/
private function getFilterTypeMap(): array
{
if ($this->filterTypeMap !== null) {
return $this->filterTypeMap;
}
$booleanType = new BooleanType();
$floatType = new FloatType();
$intType = new IntegerType();
$stringType = new StringType();
$this->filterTypeMap = [
$this->getConstant('FILTER_UNSAFE_RAW') => $stringType,
$this->getConstant('FILTER_SANITIZE_EMAIL') => $stringType,
$this->getConstant('FILTER_SANITIZE_ENCODED') => $stringType,
$this->getConstant('FILTER_SANITIZE_NUMBER_FLOAT') => $stringType,
$this->getConstant('FILTER_SANITIZE_NUMBER_INT') => $stringType,
$this->getConstant('FILTER_SANITIZE_SPECIAL_CHARS') => $stringType,
$this->getConstant('FILTER_SANITIZE_STRING') => $stringType,
$this->getConstant('FILTER_SANITIZE_URL') => $stringType,
$this->getConstant('FILTER_VALIDATE_BOOLEAN') => $booleanType,
$this->getConstant('FILTER_VALIDATE_DOMAIN') => $stringType,
$this->getConstant('FILTER_VALIDATE_EMAIL') => $stringType,
$this->getConstant('FILTER_VALIDATE_FLOAT') => $floatType,
$this->getConstant('FILTER_VALIDATE_INT') => $intType,
$this->getConstant('FILTER_VALIDATE_IP') => $stringType,
$this->getConstant('FILTER_VALIDATE_MAC') => $stringType,
$this->getConstant('FILTER_VALIDATE_REGEXP') => $stringType,
$this->getConstant('FILTER_VALIDATE_URL') => $stringType,
];
if ($this->reflectionProvider->hasConstant(new Node\Name('FILTER_SANITIZE_MAGIC_QUOTES'), null)) {
$this->filterTypeMap[$this->getConstant('FILTER_SANITIZE_MAGIC_QUOTES')] = $stringType;
}
if ($this->reflectionProvider->hasConstant(new Node\Name('FILTER_SANITIZE_ADD_SLASHES'), null)) {
$this->filterTypeMap[$this->getConstant('FILTER_SANITIZE_ADD_SLASHES')] = $stringType;
}
return $this->filterTypeMap;
}
/**
* @return array<int, list<string>>
*/
private function getFilterTypeOptions(): array
{
if ($this->filterTypeOptions !== null) {
return $this->filterTypeOptions;
}
$this->filterTypeOptions = [
$this->getConstant('FILTER_VALIDATE_INT') => ['min_range', 'max_range'],
// PHPStan does not yet support FloatRangeType
// $this->getConstant('FILTER_VALIDATE_FLOAT') => ['min_range', 'max_range'],
];
return $this->filterTypeOptions;
}
private function getConstant(string $constantName): int
{
$constant = $this->reflectionProvider->getConstant(new Node\Name($constantName), null);
$valueType = $constant->getValueType();
if (!$valueType instanceof ConstantIntegerType) {
throw new ShouldNotHappenException(sprintf('Constant %s does not have integer type.', $constantName));
}
return $valueType->getValue();
}
private function determineExactType(Type $in, int $filterValue, Type $defaultType, ?Type $flagsType): ?Type
{
if ($filterValue === $this->getConstant('FILTER_VALIDATE_BOOLEAN')) {
if ($in->isBoolean()->yes()) {
return $in;
}
}
if ($filterValue === $this->getConstant('FILTER_VALIDATE_FLOAT')) {
if ($in->isFloat()->yes()) {
return $in;
}
if ($in->isInteger()->yes()) {
return $in->toFloat();
}
}
if ($filterValue === $this->getConstant('FILTER_VALIDATE_INT')) {
if ($in->isInteger()->yes()) {
return $in;
}
if ($in instanceof ConstantFloatType) {
return $in->getValue() - (int) $in->getValue() <= PHP_FLOAT_EPSILON
? $in->toInteger()
: $defaultType;
}
if ($in instanceof ConstantStringType) {
$value = $in->getValue();
$allowOctal = $this->hasFlag($this->getConstant('FILTER_FLAG_ALLOW_OCTAL'), $flagsType);
$allowHex = $this->hasFlag($this->getConstant('FILTER_FLAG_ALLOW_HEX'), $flagsType);
if ($allowOctal && preg_match('/\A0[oO][0-7]+\z/', $value) === 1) {
$octalValue = octdec($value);
return is_int($octalValue) ? new ConstantIntegerType($octalValue) : $defaultType;
}
if ($allowHex && preg_match('/\A0[xX][0-9A-Fa-f]+\z/', $value) === 1) {
$hexValue = hexdec($value);
return is_int($hexValue) ? new ConstantIntegerType($hexValue) : $defaultType;
}
return preg_match('/\A[+-]?(?:0|[1-9][0-9]*)\z/', $value) === 1 ? $in->toInteger() : $defaultType;
}
}
if ($filterValue === $this->getConstant('FILTER_DEFAULT')) {
if (!$this->canStringBeSanitized($filterValue, $flagsType) && $in->isString()->yes()) {
return $in;
}
if ($in->isBoolean()->yes() || $in->isFloat()->yes() || $in->isInteger()->yes() || $in->isNull()->yes()) {
return $in->toString();
}
}
return null;
}
/** @param array<string, ?Type> $typeOptions */
private function applyRangeOptions(Type $type, array $typeOptions, Type $defaultType): Type
{
if (!$type->isInteger()->yes()) {
return $type;
}
$range = [];
if (isset($typeOptions['min_range'])) {
if ($typeOptions['min_range'] instanceof ConstantScalarType) {
$range['min'] = (int) $typeOptions['min_range']->getValue();
} elseif ($typeOptions['min_range'] instanceof IntegerRangeType) {
$range['min'] = $typeOptions['min_range']->getMin();
} else {
$range['min'] = null;
}
}
if (isset($typeOptions['max_range'])) {
if ($typeOptions['max_range'] instanceof ConstantScalarType) {
$range['max'] = (int) $typeOptions['max_range']->getValue();
} elseif ($typeOptions['max_range'] instanceof IntegerRangeType) {
$range['max'] = $typeOptions['max_range']->getMax();
} else {
$range['max'] = null;
}
}
if (array_key_exists('min', $range) || array_key_exists('max', $range)) {
$min = $range['min'] ?? null;
$max = $range['max'] ?? null;
$rangeType = IntegerRangeType::fromInterval($min, $max);
$rangeTypeIsSuperType = $rangeType->isSuperTypeOf($type);
if ($rangeTypeIsSuperType->no()) {
// e.g. if 9 is filtered with a range of int<17, 19>
return $defaultType;
}
if ($rangeTypeIsSuperType->yes() && !$rangeType->equals($type)) {
// e.g. if 18 or int<18, 19> are filtered with a range of int<17, 19>
return $type;
}
// Open ranges on either side means that the input is potentially not part of the range
return $min === null || $max === null ? TypeCombinator::union($rangeType, $defaultType) : $rangeType;
}
return $type;
}
private function hasOptions(Type $flagsType): TrinaryLogic
{
return $flagsType->isArray()
->and($flagsType->hasOffsetValueType(new ConstantStringType('options')));
}
/** @return array<string, ?Type> */
private function getOptions(Type $flagsType, int $filterValue): array
{
$options = [];
$optionsType = $flagsType->getOffsetValueType(new ConstantStringType('options'));
if (!$optionsType->isConstantArray()->yes()) {
return $options;
}
$optionNames = array_merge(['default'], $this->getFilterTypeOptions()[$filterValue] ?? []);
foreach ($optionNames as $optionName) {
$optionaNameType = new ConstantStringType($optionName);
if (!$optionsType->hasOffsetValueType($optionaNameType)->yes()) {
$options[$optionName] = null;
continue;
}
$options[$optionName] = $optionsType->getOffsetValueType($optionaNameType);
}
return $options;
}
private function hasFlag(int $flag, ?Type $flagsType): bool
{
if ($flagsType === null) {
return false;
}
$type = $this->getFlagsValue($flagsType);
return $type instanceof ConstantIntegerType && ($type->getValue() & $flag) === $flag;
}
private function getFlagsValue(Type $exprType): Type
{
if (!$exprType->isConstantArray()->yes()) {
return $exprType;
}
return $exprType->getOffsetValueType($this->flagsString);
}
private function canStringBeSanitized(int $filterValue, ?Type $flagsType): bool
{
// If it is a validation filter, the string will not be changed
if (($filterValue & self::VALIDATION_FILTER_BITMASK) !== 0) {
return false;
}
// FILTER_DEFAULT will not sanitize, unless it has FILTER_FLAG_STRIP_LOW,
// FILTER_FLAG_STRIP_HIGH, or FILTER_FLAG_STRIP_BACKTICK
if ($filterValue === $this->getConstant('FILTER_DEFAULT')) {
return $this->hasFlag($this->getConstant('FILTER_FLAG_STRIP_LOW'), $flagsType)
|| $this->hasFlag($this->getConstant('FILTER_FLAG_STRIP_HIGH'), $flagsType)
|| $this->hasFlag($this->getConstant('FILTER_FLAG_STRIP_BACKTICK'), $flagsType);
}
return true;
}
}