Skip to content

Commit

Permalink
Introduce CombinationsHelper
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Jun 19, 2023
1 parent 65ff783 commit 175307e
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 26 deletions.
35 changes: 35 additions & 0 deletions src/Internal/CombinationsHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php declare(strict_types = 1);

namespace PHPStan\Internal;

use function array_shift;

final class CombinationsHelper
{

/**
* @param array<mixed> $arrays
* @return iterable<mixed>
*/
public static function combinations(array $arrays): iterable
{
// from https://stackoverflow.com/a/70800936/565782 by Arnaud Le Blanc
if ($arrays === []) {
yield [];
return;
}

$head = array_shift($arrays);

foreach ($head as $elem) {
foreach (self::combinations($arrays) as $combination) {
$comb = [$elem];
foreach ($combination as $c) {
$comb[] = $c;
}
yield $comb;
}
}
}

}
28 changes: 2 additions & 26 deletions src/Type/Php/SprintfFunctionDynamicReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\Internal\CombinationsHelper;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Reflection\InitializerExprTypeResolver;
use PHPStan\Reflection\ParametersAcceptorSelector;
Expand Down Expand Up @@ -94,7 +95,7 @@ public function getTypeFromFunctionCall(
$values[] = $argType->getConstantScalarValues();
}

$combinations = $this->combinations($values);
$combinations = CombinationsHelper::combinations($values);
$returnTypes = [];
foreach ($combinations as $combination) {
$format = array_shift($combination);
Expand All @@ -120,29 +121,4 @@ public function getTypeFromFunctionCall(
return TypeCombinator::union(...$returnTypes);
}

/**
* @param array<mixed> $arrays
* @return iterable<mixed>
*/
private function combinations(array $arrays): iterable
{
// from https://stackoverflow.com/a/70800936/565782 by Arnaud Le Blanc
if ($arrays === []) {
yield [];
return;
}

$head = array_shift($arrays);

foreach ($head as $elem) {
foreach ($this->combinations($arrays) as $combination) {
$comb = [$elem];
foreach ($combination as $c) {
$comb[] = $c;
}
yield $comb;
}
}
}

}

0 comments on commit 175307e

Please sign in to comment.