Skip to content

Commit

Permalink
Merge pull request #128 from rvdbogerd/add-nullable-strict-types-for-…
Browse files Browse the repository at this point in the history
…native-arguments

Add nullable strict types for native and simple arguments
  • Loading branch information
goetas authored Dec 20, 2022
2 parents 4d69276 + e491194 commit a3fe60d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
17 changes: 17 additions & 0 deletions src/Php/ClassGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@

class ClassGenerator
{
private $strictTypes;

public function __construct(bool $strictTypes = false)
{
$this->strictTypes = $strictTypes;
}

private function handleBody(Generator\ClassGenerator $class, PHPClass $type)
{
foreach ($type->getProperties() as $prop) {
Expand Down Expand Up @@ -144,19 +151,29 @@ private function handleSetter(Generator\ClassGenerator $generator, PHPProperty $
} elseif ($type) {
if ($type->isNativeType()) {
$patramTag->setTypes($type->getPhpType());
if ($this->strictTypes) {
$parameter->setType($type->getPhpType());
}
} elseif ($p = $type->isSimpleType()) {
if (($t = $p->getType()) && !$t->isNativeType()) {
$patramTag->setTypes($t->getPhpType());
$parameter->setType($t->getPhpType());
} elseif ($t) {
$patramTag->setTypes($t->getPhpType());
if ($this->strictTypes) {
$parameter->setType($t->getPhpType());
}
}
} else {
$patramTag->setTypes($type->getPhpType());
$parameter->setType(($prop->getNullable() ? '?' : '') . $type->getPhpType());
}
}

if ($this->strictTypes && $prop->getDefault() === null) {
$parameter->setDefaultValue(null);
}

if ($prop->getNullable() && $parameter->getType()) {
$parameter->setDefaultValue(null);
}
Expand Down
7 changes: 5 additions & 2 deletions tests/AbstractGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ abstract class AbstractGenerator
{
protected $targetNs = [];
protected $aliases = [];
protected $strictTypes;

protected $phpDir;
protected $jmsDir;
Expand All @@ -28,12 +29,14 @@ abstract class AbstractGenerator

private $loader;

public function __construct(array $targetNs, array $aliases = [], $tmp = null)

public function __construct(array $targetNs, array $aliases = [], $tmp = null, bool $strictTypes = false)
{
$tmp = $tmp ?: sys_get_temp_dir();

$this->targetNs = $targetNs;
$this->aliases = $aliases;
$this->strictTypes = $strictTypes;

$this->phpDir = "$tmp/php";
$this->jmsDir = "$tmp/jms";
Expand Down Expand Up @@ -146,7 +149,7 @@ protected function writePHP(array $items)
$pathGenerator = new PhpPsr4PathGenerator($paths);

$classWriter = new PHPClassWriter($pathGenerator);
$writer = new PHPWriter($classWriter, new ClassGenerator());
$writer = new PHPWriter($classWriter, new ClassGenerator($this->strictTypes));
$writer->write($items);
}

Expand Down

0 comments on commit a3fe60d

Please sign in to comment.