Skip to content

Commit

Permalink
ConstantArrayType::getAllArrays() optimizations
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed May 6, 2020
1 parent 8bda796 commit bfe2003
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions src/Type/Constant/ConstantArrayType.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ class ConstantArrayType extends ArrayType implements ConstantType
/** @var int[] */
private $optionalKeys;

/** @var self[]|null */
private $allArrays;

/**
* @param array<int, ConstantIntegerType|ConstantStringType> $keyTypes
* @param array<int, Type> $valueTypes
Expand Down Expand Up @@ -93,7 +96,19 @@ public function getOptionalKeys(): array
*/
public function getAllArrays(): array
{
$optionalKeysCombination = $this->powerSet($this->optionalKeys);
if ($this->allArrays !== null) {
return $this->allArrays;
}

if (count($this->optionalKeys) <= 10) {
$optionalKeysCombinations = $this->powerSet($this->optionalKeys);
} else {
$optionalKeysCombinations = [
[],
$this->optionalKeys,
];
}

$requiredKeys = [];
foreach (array_keys($this->keyTypes) as $i) {
if (in_array($i, $this->optionalKeys, true)) {
Expand All @@ -103,7 +118,7 @@ public function getAllArrays(): array
}

$arrays = [];
foreach ($optionalKeysCombination as $combination) {
foreach ($optionalKeysCombinations as $combination) {
$keys = array_merge($requiredKeys, $combination);
$keyTypes = [];
$valueTypes = [];
Expand All @@ -115,7 +130,7 @@ public function getAllArrays(): array
$arrays[] = new self($keyTypes, $valueTypes, 0 /*TODO*/, []);
}

return $arrays;
return $this->allArrays = $arrays;
}

/**
Expand Down

0 comments on commit bfe2003

Please sign in to comment.