Skip to content

Commit ed8d53a

Browse files
committed
feat: add getBuilderTypeForModels method to BuilderHelper
1 parent 8d433ed commit ed8d53a

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/Methods/BuilderHelper.php

+34
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,18 @@
1717
use PHPStan\ShouldNotHappenException;
1818
use PHPStan\TrinaryLogic;
1919
use PHPStan\Type\Generic\GenericObjectType;
20+
use PHPStan\Type\ObjectType;
2021
use PHPStan\Type\Type;
22+
use PHPStan\Type\TypeCombinator;
23+
use PHPStan\Type\TypeWithClassName;
2124
use PHPStan\Type\VerbosityLevel;
2225

2326
use function array_key_exists;
2427
use function array_shift;
28+
use function collect;
2529
use function count;
2630
use function in_array;
31+
use function is_string;
2732
use function preg_split;
2833
use function substr;
2934
use function ucfirst;
@@ -232,4 +237,33 @@ public function determineBuilderName(string $modelClassName): string
232237

233238
return $returnType->describe(VerbosityLevel::value());
234239
}
240+
241+
/**
242+
* @param array<int, string|TypeWithClassName>|string|TypeWithClassName $models
243+
*
244+
* @return ($models is array<int, string|TypeWithClassName> ? Type : ObjectType)
245+
*/
246+
public function getBuilderTypeForModels(array|string|TypeWithClassName $models): Type
247+
{
248+
return collect()
249+
->wrap($models)
250+
->unique()
251+
->mapWithKeys(static function ($model) {
252+
if (is_string($model)) {
253+
return [$model => new ObjectType($model)];
254+
}
255+
256+
return [$model->getClassName() => $model];
257+
})
258+
->mapToGroups(fn ($type, $class) => [$this->determineBuilderName($class) => $type])
259+
->map(function ($models, $builder) {
260+
$builderReflection = $this->reflectionProvider->getClass($builder);
261+
262+
return $builderReflection->isGeneric()
263+
? new GenericObjectType($builder, [TypeCombinator::union(...$models)])
264+
: new ObjectType($builder);
265+
})
266+
->values()
267+
->pipe(static fn ($types) => TypeCombinator::union(...$types));
268+
}
235269
}

0 commit comments

Comments
 (0)