| 1 |
<?php declare(strict_types=1); |
| 2 |
|
| 3 |
namespace TablePress\Composer\Pcre\PHPStan; |
| 4 |
|
| 5 |
use PHPStan\Analyser\Scope; |
| 6 |
use PHPStan\Type\ArrayType; |
| 7 |
use PHPStan\Type\Constant\ConstantArrayType; |
| 8 |
use PHPStan\Type\Constant\ConstantIntegerType; |
| 9 |
use PHPStan\Type\IntersectionType; |
| 10 |
use PHPStan\Type\TypeCombinator; |
| 11 |
use PHPStan\Type\Type; |
| 12 |
use PhpParser\Node\Arg; |
| 13 |
use PHPStan\Type\Php\RegexArrayShapeMatcher; |
| 14 |
use PHPStan\Type\TypeTraverser; |
| 15 |
use PHPStan\Type\UnionType; |
| 16 |
|
| 17 |
final class PregMatchFlags |
| 18 |
{ |
| 19 |
static public function getType(?Arg $flagsArg, Scope $scope): ?Type |
| 20 |
{ |
| 21 |
if ($flagsArg === null) { |
| 22 |
return new ConstantIntegerType(PREG_UNMATCHED_AS_NULL); |
| 23 |
} |
| 24 |
|
| 25 |
$flagsType = $scope->getType($flagsArg->value); |
| 26 |
|
| 27 |
$constantScalars = $flagsType->getConstantScalarValues(); |
| 28 |
if ($constantScalars === []) { |
| 29 |
return null; |
| 30 |
} |
| 31 |
|
| 32 |
$internalFlagsTypes = []; |
| 33 |
foreach ($flagsType->getConstantScalarValues() as $constantScalarValue) { |
| 34 |
if (!is_int($constantScalarValue)) { |
| 35 |
return null; |
| 36 |
} |
| 37 |
|
| 38 |
$internalFlagsTypes[] = new ConstantIntegerType($constantScalarValue | PREG_UNMATCHED_AS_NULL); |
| 39 |
} |
| 40 |
return TypeCombinator::union(...$internalFlagsTypes); |
| 41 |
} |
| 42 |
|
| 43 |
static public function removeNullFromMatches(Type $matchesType): Type |
| 44 |
{ |
| 45 |
return TypeTraverser::map($matchesType, static function (Type $type, callable $traverse): Type { |
| 46 |
if ($type instanceof UnionType || $type instanceof IntersectionType) { |
| 47 |
return $traverse($type); |
| 48 |
} |
| 49 |
|
| 50 |
if ($type instanceof ConstantArrayType) { |
| 51 |
return new ConstantArrayType( |
| 52 |
$type->getKeyTypes(), |
| 53 |
array_map(static function (Type $valueType) use ($traverse): Type { |
| 54 |
return $traverse($valueType); |
| 55 |
}, $type->getValueTypes()), |
| 56 |
$type->getNextAutoIndexes(), |
| 57 |
[], |
| 58 |
$type->isList() |
| 59 |
); |
| 60 |
} |
| 61 |
|
| 62 |
if ($type instanceof ArrayType) { |
| 63 |
return new ArrayType($type->getKeyType(), $traverse($type->getItemType())); |
| 64 |
} |
| 65 |
|
| 66 |
return TypeCombinator::removeNull($type); |
| 67 |
}); |
| 68 |
} |
| 69 |
|
| 70 |
} |
| 71 |
|