Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 141 additions & 0 deletions src/Type/Php/UnserializeFunctionThrowTypeExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
<?php declare(strict_types = 1);

namespace PHPStan\Type\Php;

use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Php\PhpVersion;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Type\Constant\ConstantArrayType;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\DynamicFunctionThrowTypeExtension;
use PHPStan\Type\IntegerRangeType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;
use PHPStan\Type\VoidType;
use TypeError;
use function count;
use function preg_match;

/**
* unserialize() throws TypeError and ValueError for invalid $options, and
* TypeError when the data does not fit a typed property. Objects of classes
* that are not allowed are unserialized as __PHP_Incomplete_Class.
*/
#[AutowiredService]
final class UnserializeFunctionThrowTypeExtension implements DynamicFunctionThrowTypeExtension
{

public function __construct(private PhpVersion $phpVersion)
{
}

public function isFunctionSupported(FunctionReflection $functionReflection): bool
{
return $functionReflection->getName() === 'unserialize';
}

public function getThrowTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $funcCall, Scope $scope): ?Type
{
if (!$this->phpVersion->throwsValueErrorForInternalFunctions()) {
return new VoidType();
}

$args = $funcCall->getArgs();
foreach ($args as $arg) {
if ($arg->unpack || $arg->name !== null) {
return $functionReflection->getThrowType();
}
}

if (count($args) < 2) {
return new ObjectType(TypeError::class);
}

$optionsType = $scope->getNativeType($args[1]->value);
$constantArrays = $optionsType->getConstantArrays();
if (!$optionsType->isArray()->yes() || count($constantArrays) === 0) {
return $functionReflection->getThrowType();
}

$allowsNoClasses = true;
foreach ($constantArrays as $constantArray) {
if (!$this->areOptionsValid($constantArray)) {
return $functionReflection->getThrowType();
}

if ($this->allowsNoClasses($constantArray)) {
continue;
}

$allowsNoClasses = false;
}

if ($allowsNoClasses) {
return new VoidType();
}

return new ObjectType(TypeError::class);
}

private function areOptionsValid(ConstantArrayType $options): bool
{
$allowedClassesKey = new ConstantStringType('allowed_classes');
if (!$options->hasOffsetValueType($allowedClassesKey)->no()) {
$allowedClasses = $options->getOffsetValueType($allowedClassesKey);
if (!$allowedClasses->isBoolean()->yes() && !$this->isListOfClassNames($allowedClasses)) {
return false;
}
}

$maxDepthKey = new ConstantStringType('max_depth');
if (!$options->hasOffsetValueType($maxDepthKey)->no()) {
return IntegerRangeType::fromInterval(0, null)->isSuperTypeOf($options->getOffsetValueType($maxDepthKey))->yes();
}

return true;
}

private function isListOfClassNames(Type $type): bool
{
if (!$type->isArray()->yes()) {
return false;
}

if ($type->isIterableAtLeastOnce()->no()) {
return true;
}

$classNames = $type->getIterableValueType()->getConstantStrings();
if (count($classNames) === 0 || !$type->getIterableValueType()->isString()->yes()) {
return false;
}

foreach ($classNames as $className) {
if (preg_match('~^[0-9A-Za-z_\\\\\x80-\xff]*$~', $className->getValue()) !== 1) {
return false;
}
}

return true;
}

/**
* With no allowed classes, objects become __PHP_Incomplete_Class and no
* typed property can reject the data.
*/
private function allowsNoClasses(ConstantArrayType $options): bool
{
$allowedClassesKey = new ConstantStringType('allowed_classes');
if (!$options->hasOffsetValueType($allowedClassesKey)->yes()) {
return false;
}

$allowedClasses = $options->getOffsetValueType($allowedClassesKey);

return $allowedClasses->isFalse()->yes()
|| ($allowedClasses->isArray()->yes() && $allowedClasses->isIterableAtLeastOnce()->no());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -1306,4 +1306,82 @@ public function testDsMapVoidThrowType(): void
]);
}

#[RequiresPhp('>= 8.0.0')]
public function testUnserializeThrowType(): void
{
$this->analyse([__DIR__ . '/data/unserialize-throw-type.php'], [
[
'Dead catch - ValueError is never thrown in the try block.',
15,
],
[
'Dead catch - TypeError is never thrown in the try block.',
27,
],
[
'Dead catch - TypeError is never thrown in the try block.',
33,
],
[
'Dead catch - ValueError is never thrown in the try block.',
39,
],
]);
}

#[RequiresPhp('< 8.0.0')]
public function testUnserializeThrowTypeBeforePhp8(): void
{
$this->analyse([__DIR__ . '/data/unserialize-throw-type.php'], [
[
'Dead catch - ValueError is never thrown in the try block.',
15,
],
[
'Dead catch - TypeError is never thrown in the try block.',
21,
],
[
'Dead catch - TypeError is never thrown in the try block.',
27,
],
[
'Dead catch - TypeError is never thrown in the try block.',
33,
],
[
'Dead catch - ValueError is never thrown in the try block.',
39,
],
[
'Dead catch - TypeError is never thrown in the try block.',
45,
],
[
'Dead catch - ValueError is never thrown in the try block.',
51,
],
[
'Dead catch - ValueError is never thrown in the try block.',
57,
],
[
'Dead catch - TypeError is never thrown in the try block.',
63,
],
[
'Dead catch - ValueError is never thrown in the try block.',
69,
],
[
'Dead catch - TypeError is never thrown in the try block.',
75,
],
[
'Dead catch - ValueError is never thrown in the try block.',
81,
],
]);
}

}
86 changes: 86 additions & 0 deletions tests/PHPStan/Rules/Exceptions/data/unserialize-throw-type.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?php

namespace UnserializeThrowType;

class Foo
{

/**
* @param array{allowed_classes: false} $phpDocOptions
*/
public function doFoo(string $s, array $options, array $phpDocOptions, int $depth): void
{
try {
$a = unserialize($s);
} catch (\ValueError $e) {

}

try {
$a = unserialize($s);
} catch (\TypeError $e) {

}

try {
$a = unserialize($s, ['allowed_classes' => false]);
} catch (\TypeError $e) {

}

try {
$a = unserialize($s, ['allowed_classes' => [], 'max_depth' => 10]);
} catch (\TypeError $e) {

}

try {
$a = unserialize($s, ['allowed_classes' => [Foo::class], 'max_depth' => 10]);
} catch (\ValueError $e) {

}

try {
$a = unserialize($s, ['allowed_classes' => [Foo::class]]);
} catch (\TypeError $e) {

}

try {
$a = unserialize($s, ['max_depth' => -1]);
} catch (\ValueError $e) {

}

try {
$a = unserialize($s, ['allowed_classes' => ['a b']]);
} catch (\ValueError $e) {

}

try {
$a = unserialize($s, ['max_depth' => '5']);
} catch (\TypeError $e) {

}

try {
$a = unserialize($s, $options);
} catch (\ValueError $e) {

}

try {
$a = unserialize($s, $phpDocOptions);
} catch (\TypeError $e) {

}

try {
$a = unserialize($s, ['max_depth' => $depth]);
} catch (\ValueError $e) {

}
}

}
Loading