Skip to content

Commit

Permalink
Adds support for primitive arrays via docblocks (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
morrislaptop committed Nov 1, 2023
1 parent 94d1352 commit 6672e9d
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 15 deletions.
46 changes: 31 additions & 15 deletions src/PropertyFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,13 +95,18 @@ protected function extractDocBlockType(ReflectionProperty $property): ?string
* @psalm-suppress RedundantCondition
*/
if (method_exists($type, 'getCollectionValueTypes')) {
$collectionType = $type->getCollectionValueTypes()[0];
$collectionType = $type->getCollectionValueTypes()[0] ?? null;
} else {
/**
* @psalm-suppress UndefinedMethod
*/
$collectionType = $type->getCollectionValueType();
}

if (! $collectionType) {
return 'array';
}

$className = $collectionType->getClassName() ?? $collectionType->getBuiltinType();

return $className . '[]';
Expand All @@ -118,6 +123,31 @@ protected function extractDocBlockType(ReflectionProperty $property): ?string
*/
protected function createPropertyOfType(string $type)
{
switch ($type) {
case 'array':
return FakerMap::faker()->words();

case 'bool':
return FakerMap::faker()->boolean();
case 'bool[]':
return [FakerMap::faker()->boolean()];

case 'int':
return FakerMap::faker()->randomDigit();
case 'int[]':
return [FakerMap::faker()->randomDigit()];

case 'float':
return FakerMap::faker()->randomFloat();
case 'float[]':
return [FakerMap::faker()->randomFloat()];

case 'string':
return FakerMap::faker()->word();
case 'string[]':
return FakerMap::faker()->words();
}

// Handles an array of DTOs
if (strpos($type, '[]') !== false) {
$type = str_replace('[]', '', $type);
Expand All @@ -133,20 +163,6 @@ protected function createPropertyOfType(string $type)
->make();
}

switch ($type) {
case 'array':
return FakerMap::faker()->words();

case 'bool':
return FakerMap::faker()->boolean();

case 'int':
return FakerMap::faker()->randomDigit();

case 'float':
return FakerMap::faker()->randomFloat();
}

return FakerMap::faker()->word();
}

Expand Down
4 changes: 4 additions & 0 deletions tests/Popos/PersonData.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ class PersonData
public function __construct(
public $firstName,
public string $lastName,
/** @var array<string,mixed> */
public array $otherNames,
/** @var array<string,int> */
public array $luckyNumbers,
public string $email,
public string $homeAddress,
public ?string $companyName,
Expand Down

0 comments on commit 6672e9d

Please sign in to comment.