[Slim4] Add ModelUtils and StringUtils (#4855)

* [Slim4] Add StringUtils and ModelUtils classes

* [Slim4] Refresh samples
This commit is contained in:
Yuriy Belenko 2019-12-22 12:04:30 +05:00 committed by William Cheng
parent 04ac754d3e
commit ca4f718748
13 changed files with 978 additions and 3 deletions

View File

@ -42,6 +42,8 @@ public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen {
protected String psr7Implementation = "slim-psr7";
protected String mockDirName = "Mock";
protected String mockPackage = "";
protected String utilsDirName = "Utils";
protected String utilsPackage = "";
public PhpSlim4ServerCodegen() {
super();
@ -51,6 +53,7 @@ public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen {
.build();
mockPackage = invokerPackage + "\\" + mockDirName;
utilsPackage = invokerPackage + "\\" + utilsDirName;
outputFolder = "generated-code" + File.separator + "slim4";
embeddedTemplateDir = templateDir = "php-slim4-server";
@ -86,8 +89,9 @@ public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen {
super.processOpts();
if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) {
// Update the invokerPackage for the default mockPackage
// Update mockPackage and utilsPackage
mockPackage = invokerPackage + "\\" + mockDirName;
utilsPackage = invokerPackage + "\\" + utilsDirName;
}
// make mock src path available in mustache template
@ -95,6 +99,11 @@ public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen {
additionalProperties.put("mockSrcPath", "./" + toSrcPath(mockPackage, srcBasePath));
additionalProperties.put("mockTestPath", "./" + toSrcPath(mockPackage, testBasePath));
// same for utils package
additionalProperties.put("utilsPackage", utilsPackage);
additionalProperties.put("utilsSrcPath", "./" + toSrcPath(utilsPackage, srcBasePath));
additionalProperties.put("utilsTestPath", "./" + toSrcPath(utilsPackage, testBasePath));
if (additionalProperties.containsKey(PSR7_IMPLEMENTATION)) {
this.setPsr7Implementation((String) additionalProperties.get(PSR7_IMPLEMENTATION));
}
@ -132,6 +141,12 @@ public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen {
supportingFiles.add(new SupportingFile("openapi_data_mocker_interface.mustache", toSrcPath(mockPackage, srcBasePath), toInterfaceName("OpenApiDataMocker") + ".php"));
supportingFiles.add(new SupportingFile("openapi_data_mocker.mustache", toSrcPath(mockPackage, srcBasePath), "OpenApiDataMocker.php"));
supportingFiles.add(new SupportingFile("openapi_data_mocker_test.mustache", toSrcPath(mockPackage, testBasePath), "OpenApiDataMockerTest.php"));
// traits of ported utils
supportingFiles.add(new SupportingFile("string_utils_trait.mustache", toSrcPath(utilsPackage, srcBasePath), toTraitName("StringUtils") + ".php"));
supportingFiles.add(new SupportingFile("string_utils_trait_test.mustache", toSrcPath(utilsPackage, testBasePath), toTraitName("StringUtils") + "Test.php"));
supportingFiles.add(new SupportingFile("model_utils_trait.mustache", toSrcPath(utilsPackage, srcBasePath), toTraitName("ModelUtils") + ".php"));
supportingFiles.add(new SupportingFile("model_utils_trait_test.mustache", toSrcPath(utilsPackage, testBasePath), toTraitName("ModelUtils") + "Test.php"));
}
/**

View File

@ -43,11 +43,13 @@
"test": [
"@test-apis",
"@test-models",
"@test-mock"
"@test-mock",
"@test-utils"
],
"test-apis": "phpunit --testsuite Apis",
"test-models": "phpunit --testsuite Models",
"test-mock": "phpunit --testsuite Mock",
"test-utils": "phpunit --testsuite Utils",
"phpcs": "phpcs",
"phplint": "phplint ./ --exclude=vendor"
}

View File

@ -0,0 +1,132 @@
<?php
/**
* {{traitNamePrefix}}ModelUtils{{traitNameSuffix}}
*
* PHP version 7.1
*
* @package {{invokerPackage}}
* @author OpenAPI Generator team
* @link https://github.com/openapitools/openapi-generator
*/
/**{{#apiInfo}}{{#appName}}
* {{{appName}}}
*
{{/appName}}
{{#appDescription}}
* {{{appDescription}}}
{{/appDescription}}
{{#version}}
* The version of the OpenAPI document: {{{version}}}
{{/version}}
{{#infoEmail}}
* Contact: {{{infoEmail}}}
{{/infoEmail}}
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
/**
* NOTE: This class is auto generated by the openapi generator program.
* https://github.com/openapitools/openapi-generator
* Do not edit the class manually.
*/
namespace {{utilsPackage}};
use {{utilsPackage}}\{{traitNamePrefix}}StringUtils{{traitNameSuffix}};
/**
* {{traitNamePrefix}}ModelUtils{{traitNameSuffix}} Class Doc Comment
* This class duplicates functionality of ModelUtils.java and AbstractPhpCodegen.java classes.
*
* @package {{utilsPackage}}
* @author OpenAPI Generator team
* @link https://github.com/openapitools/openapi-generator
*/
trait {{traitNamePrefix}}ModelUtils{{traitNameSuffix}}
{
use {{traitNamePrefix}}StringUtils{{traitNameSuffix}};
/**
* Parses model class name from provided ref.
* @link https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#reference-object
* This method doesn't check that class exists and autoloaded.
* This is recreated method of @link modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java class.
*
* @param string $ref Reference, eg. #/components/schemas/Pet
*
* @return string|null classname or null on fail
*/
public static function getSimpleRef($ref)
{
$model = null;
if (stripos($ref, '#/components/') === 0) {
// starts with #/components/
$model = substr($ref, strrpos($ref, '/') + 1);
} elseif (stripos($ref, '#/definitions/') === 0) {
// starts with #/definitions/
$model = substr($ref, strrpos($ref, '/') + 1);
}
return $model;
}
/**
* Output the proper model name (capitalized).
* In case the name belongs to the TypeSystem it won't be renamed.
* This is recreated method of @link modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java class.
*
* @param string $name the name of the model
* @param string|null $modelNamePrefix modelNamePrefix generator option
* @param string|null $modelNameSuffix modelNameSuffix generator option
*
* @return string capitalized model name
*/
public static function toModelName(
$name,
$modelNamePrefix = {{#modelNamePrefix}}'{{modelNamePrefix}}'{{/modelNamePrefix}}{{^modelNamePrefix}}null{{/modelNamePrefix}},
$modelNameSuffix = {{#modelNameSuffix}}'{{modelNameSuffix}}'{{/modelNameSuffix}}{{^modelNameSuffix}}null{{/modelNameSuffix}}
) {
if (is_string($name) === false || empty($name)) {
return null;
}
// remove [
$name = str_replace(']', '', $name);
// Note: backslash ("\\") is allowed for e.g. "\\DateTime"
$name = preg_replace('/[^\w\\\\]+/', '_', $name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// remove underscores from start and end
$name = trim($name, '_');
// remove dollar sign
$name = str_replace('$', '', $name);
// model name cannot use reserved keyword
if (self::isReservedWord($name)) {
$name = 'model_' . $name; // e.g. return => ModelReturn (after camelize)
}
// model name starts with number
if (preg_match('/^\d.*/', $name) === 1) {
$name = 'model_' . $name; // e.g. 200Response => Model200Response (after camelize)
}
// add prefix and/or suffic only if name does not start wth \ (e.g. \DateTime)
if (preg_match('/^\\\\.*/', $name) !== 1) {
if (is_string($modelNamePrefix) && !empty($modelNamePrefix)) {
$name = $modelNamePrefix . '_' . $name;
}
if (is_string($modelNameSuffix) && !empty($modelNameSuffix)) {
$name = $name . '_' . $modelNameSuffix;
}
}
// camelize the model name
// phone_number => PhoneNumber
return self::camelize($name);
}
}
{{/apiInfo}}

View File

@ -0,0 +1,111 @@
<?php
/**
* {{traitNamePrefix}}ModelUtils{{traitNameSuffix}}Test
*
* PHP version 7.1
*
* @package {{invokerPackage}}
* @author OpenAPI Generator team
* @link https://github.com/openapitools/openapi-generator
*/
/**{{#apiInfo}}{{#appName}}
* {{{appName}}}
*
{{/appName}}
{{#appDescription}}
* {{{appDescription}}}
{{/appDescription}}
{{#version}}
* The version of the OpenAPI document: {{{version}}}
{{/version}}
{{#infoEmail}}
* Contact: {{{infoEmail}}}
{{/infoEmail}}
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
/**
* NOTE: This class is auto generated by the openapi generator program.
* https://github.com/openapitools/openapi-generator
* Do not edit the class manually.
*/
namespace {{utilsPackage}};
use {{utilsPackage}}\{{traitNamePrefix}}ModelUtils{{traitNameSuffix}} as ModelUtils;
use PHPUnit\Framework\TestCase;
/**
* {{traitNamePrefix}}ModelUtils{{traitNameSuffix}}Test Class Doc Comment
*
* @package {{utilsPackage}}
* @author OpenAPI Generator team
* @link https://github.com/openapitools/openapi-generator
* @coversDefaultClass \{{utilsPackage}}\{{traitNamePrefix}}ModelUtils{{traitNameSuffix}}
*/
class {{traitNamePrefix}}ModelUtils{{traitNameSuffix}}Test extends TestCase
{
/**
* @covers ::getSimpleRef
* @dataProvider provideRefs
*/
public function testGetSimpleRef($ref, $expectedRef)
{
$this->assertSame($expectedRef, ModelUtils::getSimpleRef($ref));
}
public function provideRefs()
{
return [
'Reference Object OAS 3.0' => [
'#/components/schemas/Pet', 'Pet',
],
'Reference Object Swagger 2.0' => [
'#/definitions/Pet', 'Pet',
],
'Underscored classname' => [
'#/components/schemas/_foobar_Objects', '_foobar_Objects',
],
'Relative Documents With Embedded Schema' => [
'definitions.json#/Pet', null,
],
'null as argument' => [
null, null,
],
'number as argument' => [
156, null,
],
];
}
/**
* @covers ::toModelName
* @dataProvider provideModelNames
*/
public function testToModelName($name, $prefix, $suffix, $expectedModel)
{
$this->assertSame($expectedModel, ModelUtils::toModelName($name, $prefix, $suffix));
}
public function provideModelNames()
{
return [
// fixtures from modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/StringUtilsTest.java
['abcd', null, null, 'Abcd'],
['some-value', null, null, 'SomeValue'],
['some_value', null, null, 'SomeValue'],
['$type', null, null, 'Type'],
['123', null, null, 'Model123'],
['$123', null, null, 'Model123'],
['return', null, null, 'ModelReturn'],
['200Response', null, null, 'Model200Response'],
['abcd', 'SuperModel', null, 'SuperModelAbcd'],
['abcd', null, 'WithEnd', 'AbcdWithEnd'],
['abcd', 'WithStart', 'AndEnd', 'WithStartAbcdAndEnd'],
['_foobar_Objects', null, null, 'FoobarObjects'],
[null, null, null, null],
];
}
}
{{/apiInfo}}

View File

@ -20,12 +20,16 @@
<testsuite name="Mock">
<directory>{{mockTestPath}}</directory>
</testsuite>
<testsuite name="Utils">
<directory>{{utilsTestPath}}</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">{{apiSrcPath}}</directory>
<directory suffix=".php">{{modelSrcPath}}</directory>
<directory suffix=".php">{{mockSrcPath}}</directory>
<directory suffix=".php">{{utilsSrcPath}}</directory>
</whitelist>
</filter>
<php>

View File

@ -0,0 +1,141 @@
<?php
/**
* {{traitNamePrefix}}StringUtils{{traitNameSuffix}}
*
* PHP version 7.1
*
* @package {{invokerPackage}}
* @author OpenAPI Generator team
* @link https://github.com/openapitools/openapi-generator
*/
/**{{#apiInfo}}{{#appName}}
* {{{appName}}}
*
{{/appName}}
{{#appDescription}}
* {{{appDescription}}}
{{/appDescription}}
{{#version}}
* The version of the OpenAPI document: {{{version}}}
{{/version}}
{{#infoEmail}}
* Contact: {{{infoEmail}}}
{{/infoEmail}}
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
/**
* NOTE: This class is auto generated by the openapi generator program.
* https://github.com/openapitools/openapi-generator
* Do not edit the class manually.
*/
namespace {{utilsPackage}};
/**
* {{traitNamePrefix}}StringUtils{{traitNameSuffix}} Class Doc Comment
* This class duplicates functionality of StringUtils.java and AbstractPhpCodegen.java classes.
*
* @package {{utilsPackage}}
* @author OpenAPI Generator team
* @link https://github.com/openapitools/openapi-generator
*/
trait {{traitNamePrefix}}StringUtils{{traitNameSuffix}}
{
/**
* Camelize name (parameter, property, method, etc)
* This is recreated method of @link modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/StringUtils.java class.
*
* @param string $word string to be camelize
* @param bool $lowercaseFirstLetter lower case for first letter if set to true
*
* @return string camelized string
*/
public static function camelize($word, $lowercaseFirstLetter = false)
{
// Replace all slashes with dots (package separator)
$p = '/\/(.?)/';
$word = preg_replace($p, '.$1', $word);
// case out dots
$parts = explode('.', $word);
$str = '';
foreach ($parts as $z) {
if (strlen($z) > 0) {
$str .= strtoupper(substr($z, 0, 1)) . substr($z, 1);
}
}
$word = $str;
// Uppercase the class name.
$p = '/(\.?)(\w)([^\.]*)$/';
$word = preg_replace_callback($p, function ($matches) {
$rep = $matches[1] . strtoupper($matches[2]) . $matches[3];
$rep = preg_replace('/\$/', '\\\$', $rep);
return $rep;
}, $word);
// Remove all underscores (underscore_case to camelCase)
$p = '/(_)(.)/';
while (preg_match($p, $word, $matches) === 1) {
$original = $matches[2][0];
$upperCase = strtoupper($original);
if ($original === $upperCase) {
$word = preg_replace($p, '$2', $word);
} else {
$word = preg_replace($p, $upperCase, $word);
}
}
// Remove all hyphens (hyphen-case to camelCase)
$p = '/(-)(.)/';
while (preg_match($p, $word, $matches) === 1) {
$upperCase = strtoupper($matches[2][0]);
$word = preg_replace($p, $upperCase, $word);
}
if ($lowercaseFirstLetter === true && strlen($word) > 0) {
$i = 0;
$charAt = substr($word, $i, 1);
while (
$i + 1 < strlen($word)
&& !(
($charAt >= 'a' && $charAt <= 'z')
|| ($charAt >= 'A' && $charAt <= 'Z')
)
) {
$i++;
$charAt = substr($word, $i, 1);
}
$i++;
$word = strtolower(substr($word, 0, $i)) . substr($word, $i);
}
// remove all underscore
$word = str_replace('_', '', $word);
return $word;
}
/**
* Checks whether string is reserved php keyword.
* This is recreated method of @link modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java class.
*
* @param string $word Checked string
*
* @return bool
*/
public static function isReservedWord($word)
{
if (is_string($word) === false) {
return false;
}
// __halt_compiler is ommited because class names with underscores not allowed anyway
return in_array(
strtolower($word),
['abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone', 'const', 'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'include', 'include_once', 'instanceof', 'insteadof', 'interface', 'isset', 'list', 'namespace', 'new', 'or', 'print', 'private', 'protected', 'public', 'require', 'require_once', 'return', 'static', 'switch', 'throw', 'trait', 'try', 'unset', 'use', 'var', 'while', 'xor']
);
}
}
{{/apiInfo}}

View File

@ -0,0 +1,108 @@
<?php
/**
* {{traitNamePrefix}}StringUtils{{traitNameSuffix}}Test
*
* PHP version 7.1
*
* @package {{invokerPackage}}
* @author OpenAPI Generator team
* @link https://github.com/openapitools/openapi-generator
*/
/**{{#apiInfo}}{{#appName}}
* {{{appName}}}
*
{{/appName}}
{{#appDescription}}
* {{{appDescription}}}
{{/appDescription}}
{{#version}}
* The version of the OpenAPI document: {{{version}}}
{{/version}}
{{#infoEmail}}
* Contact: {{{infoEmail}}}
{{/infoEmail}}
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
/**
* NOTE: This class is auto generated by the openapi generator program.
* https://github.com/openapitools/openapi-generator
* Do not edit the class manually.
*/
namespace {{utilsPackage}};
use {{utilsPackage}}\{{traitNamePrefix}}StringUtils{{traitNameSuffix}} as StringUtils;
use PHPUnit\Framework\TestCase;
/**
* {{traitNamePrefix}}StringUtils{{traitNameSuffix}}Test Class Doc Comment
*
* @package {{utilsPackage}}
* @author OpenAPI Generator team
* @link https://github.com/openapitools/openapi-generator
* @coversDefaultClass \{{utilsPackage}}\{{traitNamePrefix}}StringUtils{{traitNameSuffix}}
*/
class {{traitNamePrefix}}StringUtils{{traitNameSuffix}}Test extends TestCase
{
/**
* @covers ::camelize
* @dataProvider provideWordsForCamelizeTest
*/
public function testCamelize($word, $lowercaseFirstLetter, $expectedWord)
{
$this->assertSame($expectedWord, StringUtils::camelize($word, $lowercaseFirstLetter));
}
public function provideWordsForCamelizeTest()
{
return [
// fixtures from modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/StringUtilsTest.java
['openApiServer/model/pet', null, 'OpenApiServerModelPet'],
['abcd', null, 'Abcd'],
['some-value', null, 'SomeValue'],
['some-Value', null, 'SomeValue'],
['some_value', null, 'SomeValue'],
['some_Value', null, 'SomeValue'],
['$type', null, '$Type'],
['abcd', true, 'abcd'],
['some-value', true, 'someValue'],
['some_value', true, 'someValue'],
['Abcd', true, 'abcd'],
['$type', true, '$type'],
['123', true, '123'],
['$123', true, '$123'],
];
}
/**
* @covers ::isReservedWord
* @dataProvider provideWordsForIsReservedTest
*/
public function testisReservedWord($word, $expected)
{
$this->assertSame($expected, StringUtils::isReservedWord($word));
}
public function provideWordsForIsReservedTest()
{
return [
['return', true],
['switch', true],
['class', true],
['interface', true],
['ABSTRACT', true],
['Trait', true],
['final', true],
['foobar', false],
['DateTime', false],
['Pet', false],
[123, false],
[null, false],
];
}
}
{{/apiInfo}}

View File

@ -30,11 +30,13 @@
"test": [
"@test-apis",
"@test-models",
"@test-mock"
"@test-mock",
"@test-utils"
],
"test-apis": "phpunit --testsuite Apis",
"test-models": "phpunit --testsuite Models",
"test-mock": "phpunit --testsuite Mock",
"test-utils": "phpunit --testsuite Utils",
"phpcs": "phpcs",
"phplint": "phplint ./ --exclude=vendor"
}

View File

@ -0,0 +1,123 @@
<?php
/**
* ModelUtilsTrait
*
* PHP version 7.1
*
* @package OpenAPIServer
* @author OpenAPI Generator team
* @link https://github.com/openapitools/openapi-generator
*/
/**
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
/**
* NOTE: This class is auto generated by the openapi generator program.
* https://github.com/openapitools/openapi-generator
* Do not edit the class manually.
*/
namespace OpenAPIServer\Utils;
use OpenAPIServer\Utils\StringUtilsTrait;
/**
* ModelUtilsTrait Class Doc Comment
* This class duplicates functionality of ModelUtils.java and AbstractPhpCodegen.java classes.
*
* @package OpenAPIServer\Utils
* @author OpenAPI Generator team
* @link https://github.com/openapitools/openapi-generator
*/
trait ModelUtilsTrait
{
use StringUtilsTrait;
/**
* Parses model class name from provided ref.
* @link https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#reference-object
* This method doesn't check that class exists and autoloaded.
* This is recreated method of @link modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java class.
*
* @param string $ref Reference, eg. #/components/schemas/Pet
*
* @return string|null classname or null on fail
*/
public static function getSimpleRef($ref)
{
$model = null;
if (stripos($ref, '#/components/') === 0) {
// starts with #/components/
$model = substr($ref, strrpos($ref, '/') + 1);
} elseif (stripos($ref, '#/definitions/') === 0) {
// starts with #/definitions/
$model = substr($ref, strrpos($ref, '/') + 1);
}
return $model;
}
/**
* Output the proper model name (capitalized).
* In case the name belongs to the TypeSystem it won't be renamed.
* This is recreated method of @link modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java class.
*
* @param string $name the name of the model
* @param string|null $modelNamePrefix modelNamePrefix generator option
* @param string|null $modelNameSuffix modelNameSuffix generator option
*
* @return string capitalized model name
*/
public static function toModelName(
$name,
$modelNamePrefix = null,
$modelNameSuffix = null
) {
if (is_string($name) === false || empty($name)) {
return null;
}
// remove [
$name = str_replace(']', '', $name);
// Note: backslash ("\\") is allowed for e.g. "\\DateTime"
$name = preg_replace('/[^\w\\\\]+/', '_', $name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// remove underscores from start and end
$name = trim($name, '_');
// remove dollar sign
$name = str_replace('$', '', $name);
// model name cannot use reserved keyword
if (self::isReservedWord($name)) {
$name = 'model_' . $name; // e.g. return => ModelReturn (after camelize)
}
// model name starts with number
if (preg_match('/^\d.*/', $name) === 1) {
$name = 'model_' . $name; // e.g. 200Response => Model200Response (after camelize)
}
// add prefix and/or suffic only if name does not start wth \ (e.g. \DateTime)
if (preg_match('/^\\\\.*/', $name) !== 1) {
if (is_string($modelNamePrefix) && !empty($modelNamePrefix)) {
$name = $modelNamePrefix . '_' . $name;
}
if (is_string($modelNameSuffix) && !empty($modelNameSuffix)) {
$name = $name . '_' . $modelNameSuffix;
}
}
// camelize the model name
// phone_number => PhoneNumber
return self::camelize($name);
}
}

View File

@ -0,0 +1,132 @@
<?php
/**
* StringUtilsTrait
*
* PHP version 7.1
*
* @package OpenAPIServer
* @author OpenAPI Generator team
* @link https://github.com/openapitools/openapi-generator
*/
/**
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
/**
* NOTE: This class is auto generated by the openapi generator program.
* https://github.com/openapitools/openapi-generator
* Do not edit the class manually.
*/
namespace OpenAPIServer\Utils;
/**
* StringUtilsTrait Class Doc Comment
* This class duplicates functionality of StringUtils.java and AbstractPhpCodegen.java classes.
*
* @package OpenAPIServer\Utils
* @author OpenAPI Generator team
* @link https://github.com/openapitools/openapi-generator
*/
trait StringUtilsTrait
{
/**
* Camelize name (parameter, property, method, etc)
* This is recreated method of @link modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/StringUtils.java class.
*
* @param string $word string to be camelize
* @param bool $lowercaseFirstLetter lower case for first letter if set to true
*
* @return string camelized string
*/
public static function camelize($word, $lowercaseFirstLetter = false)
{
// Replace all slashes with dots (package separator)
$p = '/\/(.?)/';
$word = preg_replace($p, '.$1', $word);
// case out dots
$parts = explode('.', $word);
$str = '';
foreach ($parts as $z) {
if (strlen($z) > 0) {
$str .= strtoupper(substr($z, 0, 1)) . substr($z, 1);
}
}
$word = $str;
// Uppercase the class name.
$p = '/(\.?)(\w)([^\.]*)$/';
$word = preg_replace_callback($p, function ($matches) {
$rep = $matches[1] . strtoupper($matches[2]) . $matches[3];
$rep = preg_replace('/\$/', '\\\$', $rep);
return $rep;
}, $word);
// Remove all underscores (underscore_case to camelCase)
$p = '/(_)(.)/';
while (preg_match($p, $word, $matches) === 1) {
$original = $matches[2][0];
$upperCase = strtoupper($original);
if ($original === $upperCase) {
$word = preg_replace($p, '$2', $word);
} else {
$word = preg_replace($p, $upperCase, $word);
}
}
// Remove all hyphens (hyphen-case to camelCase)
$p = '/(-)(.)/';
while (preg_match($p, $word, $matches) === 1) {
$upperCase = strtoupper($matches[2][0]);
$word = preg_replace($p, $upperCase, $word);
}
if ($lowercaseFirstLetter === true && strlen($word) > 0) {
$i = 0;
$charAt = substr($word, $i, 1);
while (
$i + 1 < strlen($word)
&& !(
($charAt >= 'a' && $charAt <= 'z')
|| ($charAt >= 'A' && $charAt <= 'Z')
)
) {
$i++;
$charAt = substr($word, $i, 1);
}
$i++;
$word = strtolower(substr($word, 0, $i)) . substr($word, $i);
}
// remove all underscore
$word = str_replace('_', '', $word);
return $word;
}
/**
* Checks whether string is reserved php keyword.
* This is recreated method of @link modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java class.
*
* @param string $word Checked string
*
* @return bool
*/
public static function isReservedWord($word)
{
if (is_string($word) === false) {
return false;
}
// __halt_compiler is ommited because class names with underscores not allowed anyway
return in_array(
strtolower($word),
['abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone', 'const', 'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'include', 'include_once', 'instanceof', 'insteadof', 'interface', 'isset', 'list', 'namespace', 'new', 'or', 'print', 'private', 'protected', 'public', 'require', 'require_once', 'return', 'static', 'switch', 'throw', 'trait', 'try', 'unset', 'use', 'var', 'while', 'xor']
);
}
}

View File

@ -20,12 +20,16 @@
<testsuite name="Mock">
<directory>./test/Mock</directory>
</testsuite>
<testsuite name="Utils">
<directory>./test/Utils</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./lib/Api</directory>
<directory suffix=".php">./lib/Model</directory>
<directory suffix=".php">./lib/Mock</directory>
<directory suffix=".php">./lib/Utils</directory>
</whitelist>
</filter>
<php>

View File

@ -0,0 +1,102 @@
<?php
/**
* ModelUtilsTraitTest
*
* PHP version 7.1
*
* @package OpenAPIServer
* @author OpenAPI Generator team
* @link https://github.com/openapitools/openapi-generator
*/
/**
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
/**
* NOTE: This class is auto generated by the openapi generator program.
* https://github.com/openapitools/openapi-generator
* Do not edit the class manually.
*/
namespace OpenAPIServer\Utils;
use OpenAPIServer\Utils\ModelUtilsTrait as ModelUtils;
use PHPUnit\Framework\TestCase;
/**
* ModelUtilsTraitTest Class Doc Comment
*
* @package OpenAPIServer\Utils
* @author OpenAPI Generator team
* @link https://github.com/openapitools/openapi-generator
* @coversDefaultClass \OpenAPIServer\Utils\ModelUtilsTrait
*/
class ModelUtilsTraitTest extends TestCase
{
/**
* @covers ::getSimpleRef
* @dataProvider provideRefs
*/
public function testGetSimpleRef($ref, $expectedRef)
{
$this->assertSame($expectedRef, ModelUtils::getSimpleRef($ref));
}
public function provideRefs()
{
return [
'Reference Object OAS 3.0' => [
'#/components/schemas/Pet', 'Pet',
],
'Reference Object Swagger 2.0' => [
'#/definitions/Pet', 'Pet',
],
'Underscored classname' => [
'#/components/schemas/_foobar_Objects', '_foobar_Objects',
],
'Relative Documents With Embedded Schema' => [
'definitions.json#/Pet', null,
],
'null as argument' => [
null, null,
],
'number as argument' => [
156, null,
],
];
}
/**
* @covers ::toModelName
* @dataProvider provideModelNames
*/
public function testToModelName($name, $prefix, $suffix, $expectedModel)
{
$this->assertSame($expectedModel, ModelUtils::toModelName($name, $prefix, $suffix));
}
public function provideModelNames()
{
return [
// fixtures from modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/StringUtilsTest.java
['abcd', null, null, 'Abcd'],
['some-value', null, null, 'SomeValue'],
['some_value', null, null, 'SomeValue'],
['$type', null, null, 'Type'],
['123', null, null, 'Model123'],
['$123', null, null, 'Model123'],
['return', null, null, 'ModelReturn'],
['200Response', null, null, 'Model200Response'],
['abcd', 'SuperModel', null, 'SuperModelAbcd'],
['abcd', null, 'WithEnd', 'AbcdWithEnd'],
['abcd', 'WithStart', 'AndEnd', 'WithStartAbcdAndEnd'],
['_foobar_Objects', null, null, 'FoobarObjects'],
[null, null, null, null],
];
}
}

View File

@ -0,0 +1,99 @@
<?php
/**
* StringUtilsTraitTest
*
* PHP version 7.1
*
* @package OpenAPIServer
* @author OpenAPI Generator team
* @link https://github.com/openapitools/openapi-generator
*/
/**
* OpenAPI Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
/**
* NOTE: This class is auto generated by the openapi generator program.
* https://github.com/openapitools/openapi-generator
* Do not edit the class manually.
*/
namespace OpenAPIServer\Utils;
use OpenAPIServer\Utils\StringUtilsTrait as StringUtils;
use PHPUnit\Framework\TestCase;
/**
* StringUtilsTraitTest Class Doc Comment
*
* @package OpenAPIServer\Utils
* @author OpenAPI Generator team
* @link https://github.com/openapitools/openapi-generator
* @coversDefaultClass \OpenAPIServer\Utils\StringUtilsTrait
*/
class StringUtilsTraitTest extends TestCase
{
/**
* @covers ::camelize
* @dataProvider provideWordsForCamelizeTest
*/
public function testCamelize($word, $lowercaseFirstLetter, $expectedWord)
{
$this->assertSame($expectedWord, StringUtils::camelize($word, $lowercaseFirstLetter));
}
public function provideWordsForCamelizeTest()
{
return [
// fixtures from modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/StringUtilsTest.java
['openApiServer/model/pet', null, 'OpenApiServerModelPet'],
['abcd', null, 'Abcd'],
['some-value', null, 'SomeValue'],
['some-Value', null, 'SomeValue'],
['some_value', null, 'SomeValue'],
['some_Value', null, 'SomeValue'],
['$type', null, '$Type'],
['abcd', true, 'abcd'],
['some-value', true, 'someValue'],
['some_value', true, 'someValue'],
['Abcd', true, 'abcd'],
['$type', true, '$type'],
['123', true, '123'],
['$123', true, '$123'],
];
}
/**
* @covers ::isReservedWord
* @dataProvider provideWordsForIsReservedTest
*/
public function testisReservedWord($word, $expected)
{
$this->assertSame($expected, StringUtils::isReservedWord($word));
}
public function provideWordsForIsReservedTest()
{
return [
['return', true],
['switch', true],
['class', true],
['interface', true],
['ABSTRACT', true],
['Trait', true],
['final', true],
['foobar', false],
['DateTime', false],
['Pet', false],
[123, false],
[null, false],
];
}
}