Skip to content

Commit

Permalink
feat: support for mapping inner nullable types in arrays (#52)
Browse files Browse the repository at this point in the history
* feat: support for mapping inner nullable types in arrays

* resolve PR comments
  • Loading branch information
asadali214 authored Jun 11, 2024
1 parent 9106d0e commit 407b455
Show file tree
Hide file tree
Showing 4 changed files with 320 additions and 262 deletions.
10 changes: 7 additions & 3 deletions src/JsonMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ class JsonMapper

/**
* An array of directives from php defined configuration files.
*
*
* @var array|null Array of values from the configuration files.
*/
protected $config = null;
Expand All @@ -114,7 +114,7 @@ class JsonMapper

/**
* Constructor for JsonMapper.
*
*
* @throws JsonMapperException
*/
function __construct()
Expand Down Expand Up @@ -488,6 +488,9 @@ protected function getMappedValue(
}

if ($array !== null) {
if ($this->isNullable($subtype)) {
$subtype = $this->removeNullable($subtype);
}
if (!$this->isSimpleType($subtype)) {
$subtype = $this->getFullNamespace($subtype, $namespace);
}
Expand Down Expand Up @@ -1901,7 +1904,8 @@ protected function removeNullable($type)
{
return substr(
str_ireplace('|null|', '|', '|' . $type . '|'),
1, -1
1,
-1
);
}

Expand Down
26 changes: 17 additions & 9 deletions src/TypeCombination.php
Original file line number Diff line number Diff line change
Expand Up @@ -220,15 +220,23 @@ public function extractSimilar($group)
*/
public static function extractTypeInfo($type)
{
$mapStart = 'array<string,';
// Check if container is array or map?
$isMap = substr($type, -1) == '>' && strpos($type, $mapStart) === 0;
$isArray = substr($type, -2) == '[]';
// Extracting inner type for arrays/maps
// Inner type will be same as actual type for non-container type
$innerType = $isMap ? substr($type, strlen($mapStart), -1)
: ($isArray ? substr($type, 0, -2) : $type);
return [$isMap, $isArray, $innerType];
// Check if the type is map, i.e. wrapped in array<string,...>
if (preg_match('/^array<string,.*>$/', $type)) {
return [true, false, substr($type, strlen('array<string,'), -1)];
}

// Check if the type is array, i.e. ends with '[]'
if (preg_match('/\[]$/', $type)) {
return [false, true, substr($type, 0, -2)];
}

// Check if the type is array, i.e. wrapped in 'array<...>'
if (preg_match('/^array<.*>$/', $type)) {
return [false, true, substr($type, strlen('array<'), -1)];
}

// If the type does not match the array formats, return the original type
return [false, false, $type];
}

/**
Expand Down
Loading

0 comments on commit 407b455

Please sign in to comment.