From d4069404530b58f3c68f3a485a8e5a0795da4ba4 Mon Sep 17 00:00:00 2001 From: Sys <28715512+sys-001@users.noreply.github.com> Date: Fri, 18 Jun 2021 17:13:05 +0200 Subject: [PATCH] Major fixes, new JSON schema field for types: 'optional' --- src/Generator.php | 7 +++---- src/StubCreator.php | 36 +++++++++++++++++++++++++++++------- 2 files changed, 32 insertions(+), 11 deletions(-) diff --git a/src/Generator.php b/src/Generator.php index e89c38f..2883aae 100644 --- a/src/Generator.php +++ b/src/Generator.php @@ -215,10 +215,9 @@ class Generator ENT_QUOTES ); } else { - $parsedData['description'] = htmlspecialchars_decode( - strip_tags($fieldData[2]->innerHtml), - ENT_QUOTES - ); + $description = htmlspecialchars_decode(strip_tags($fieldData[2]->innerHtml), ENT_QUOTES); + $parsedData['optional'] = str_starts_with($description, 'Optional.'); + $parsedData['description'] = $description; } $parsedFields[] = $parsedData; } diff --git a/src/StubCreator.php b/src/StubCreator.php index 359b86e..fcfc9df 100644 --- a/src/StubCreator.php +++ b/src/StubCreator.php @@ -41,6 +41,11 @@ class StubCreator $this->namespace = $namespace; } + private static function toCamelCase(string $str): string + { + return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $str)))); + } + /** * @param array $fieldTypes * @param PhpNamespace $phpNamespace @@ -107,13 +112,23 @@ class StubCreator $response = $phpNamespace->addClass('Response') ->setType('class'); $response->addProperty('ok') - ->setPublic(); + ->setPublic() + ->setType(Type::BOOL); $response->addProperty('result') - ->setPublic(); + ->setPublic() + ->setType(Type::MIXED) + ->setNullable(true) + ->setValue(null); $response->addProperty('error_code') - ->setPublic(); + ->setPublic() + ->setType(Type::INT) + ->setNullable(true) + ->setValue(null); $response->addProperty('description') - ->setPublic(); + ->setPublic() + ->setType(Type::STRING) + ->setNullable(true) + ->setValue(null); return [ 'Response' => $file ]; @@ -136,11 +151,17 @@ class StubCreator $field['types'], $phpNamespace ); - $type_property = $typeClass->addProperty($field['name']) + $fieldName = self::toCamelCase($field['name']); + $typeProperty = $typeClass->addProperty($fieldName) ->setPublic() ->setType($fieldTypes); + if ($field['optional']) { + $typeProperty->setNullable(true) + ->setValue(null); + $fieldComments .= '|null'; + } if (!empty($fieldComments)) { - $type_property->addComment($fieldComments); + $typeProperty->addComment($fieldComments); } } $types[$type['name']] = $file; @@ -187,7 +208,8 @@ class StubCreator ); foreach ($fields as $field) { $types = $this->parseApiFieldTypes($field['types'], $phpNamespace)['types']; - $parameter = $function->addParameter($field['name']) + $fieldName = self::toCamelCase($field['name']); + $parameter = $function->addParameter($fieldName) ->setType($types); if (!$field['required']) { $parameter->setNullable()