-
-
Notifications
You must be signed in to change notification settings - Fork 183
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add PHP JsonSerializable Preset (#1491)
- Loading branch information
1 parent
dd7b4ae
commit b1d2f62
Showing
11 changed files
with
336 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
# PHP Generate JSON Serializable Models Example | ||
|
||
A basic example of how to use Modelina and output PHP model that supports JSON serialization. | ||
|
||
## How to run this example | ||
|
||
Run this example using: | ||
|
||
```sh | ||
npm i && npm run start | ||
``` | ||
|
||
If you are on Windows, use the `start:windows` script instead: | ||
|
||
```sh | ||
npm i && npm run start:windows | ||
``` |
28 changes: 28 additions & 0 deletions
28
examples/php-generate-json-serializable-preset/__snapshots__/index.spec.ts.snap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
// Jest Snapshot v1, https://goo.gl/fbAQLP | ||
|
||
exports[`Should be able to render PHP and should log expected output to console 1`] = ` | ||
Array [ | ||
"<?php | ||
declare(strict_types=1); | ||
namespace Asyncapi; | ||
final class Root implements \\\\JsonSerializable | ||
{ | ||
private ?string $email; | ||
public function getEmail(): ?string { return $this->email; } | ||
public function setEmail(?string $email): void { $this->email = $email; } | ||
public function jsonSerialize(): array | ||
{ | ||
return [ | ||
'email' => $this->email, | ||
]; | ||
} | ||
} | ||
", | ||
] | ||
`; |
15 changes: 15 additions & 0 deletions
15
examples/php-generate-json-serializable-preset/index.spec.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
const spy = jest.spyOn(global.console, 'log').mockImplementation(() => { | ||
return; | ||
}); | ||
import { generate } from './index'; | ||
|
||
describe('Should be able to render PHP', () => { | ||
afterAll(() => { | ||
jest.restoreAllMocks(); | ||
}); | ||
test('and should log expected output to console', async () => { | ||
await generate(); | ||
expect(spy.mock.calls.length).toEqual(1); | ||
expect(spy.mock.calls[0]).toMatchSnapshot(); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
import { | ||
OutputModel, | ||
PHP_JSON_SERIALIZABLE_PRESET, | ||
PhpGenerator | ||
} from '../../src'; | ||
|
||
const generator: PhpGenerator = new PhpGenerator({ | ||
presets: [PHP_JSON_SERIALIZABLE_PRESET] | ||
}); | ||
const jsonSchemaDraft7 = { | ||
$schema: 'http://json-schema.org/draft-07/schema#', | ||
type: 'object', | ||
additionalProperties: false, | ||
properties: { | ||
email: { | ||
type: 'string', | ||
format: 'email' | ||
} | ||
} | ||
}; | ||
|
||
export async function generate(): Promise<void> { | ||
const models: OutputModel[] = await generator.generateCompleteModels( | ||
jsonSchemaDraft7, | ||
{} | ||
); | ||
for (const model of models) { | ||
console.log(model.result); | ||
} | ||
} | ||
if (require.main === module) { | ||
generate(); | ||
} |
10 changes: 10 additions & 0 deletions
10
examples/php-generate-json-serializable-preset/package-lock.json
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
10 changes: 10 additions & 0 deletions
10
examples/php-generate-json-serializable-preset/package.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
{ | ||
"config" : { "example_name" : "php-generate-json-serializable-preset" }, | ||
"scripts": { | ||
"install": "cd ../.. && npm i", | ||
"start": "../../node_modules/.bin/ts-node --cwd ../../ ./examples/$npm_package_config_example_name/index.ts", | ||
"start:windows": "..\\..\\node_modules\\.bin\\ts-node --cwd ..\\..\\ .\\examples\\%npm_package_config_example_name%\\index.ts", | ||
"test": "../../node_modules/.bin/jest --config=../../jest.config.js ./examples/$npm_package_config_example_name/index.spec.ts", | ||
"test:windows": "..\\..\\node_modules\\.bin\\jest --config=..\\..\\jest.config.js examples/%npm_package_config_example_name%/index.spec.ts" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
import { PhpPreset } from '../PhpPreset'; | ||
import { PhpRenderer } from '../PhpRenderer'; | ||
import { | ||
ConstrainedDictionaryModel, | ||
ConstrainedMetaModel | ||
} from '../../../models'; | ||
|
||
function renderSelf({ | ||
content | ||
}: { | ||
content: string; | ||
renderer: PhpRenderer<ConstrainedMetaModel>; | ||
}): string { | ||
const contentLines = content.split('\n'); | ||
contentLines[0] += ` implements \\JsonSerializable`; | ||
|
||
return contentLines.join('\n'); | ||
} | ||
|
||
/** | ||
* Preset, which implements PHP’s JsonSerializable interface. | ||
* | ||
* Using this will allow to json serialize the model using `json_encode()`. | ||
* | ||
* @implements {PhpPreset} | ||
*/ | ||
export const PHP_JSON_SERIALIZABLE_PRESET: PhpPreset = { | ||
class: { | ||
self({ content, renderer }): string { | ||
return renderSelf({ content, renderer }); | ||
}, | ||
additionalContent({ renderer, model, content }): string { | ||
const serializedProperties = Object.values(model.properties).map( | ||
(property) => { | ||
if ( | ||
property.property instanceof ConstrainedDictionaryModel && | ||
property.property.serializationType === 'unwrap' | ||
) { | ||
return `...$this->${property.propertyName},`; | ||
} | ||
|
||
return `'${property.unconstrainedPropertyName}' => $this->${property.propertyName},`; | ||
} | ||
); | ||
|
||
return ( | ||
content + | ||
renderer.renderBlock([ | ||
'public function jsonSerialize(): array', | ||
'{', | ||
renderer.indent( | ||
renderer.renderBlock([ | ||
'return [', | ||
renderer.indent(renderer.renderBlock(serializedProperties)), | ||
'];' | ||
]) | ||
), | ||
'}' | ||
]) | ||
); | ||
} | ||
}, | ||
enum: { | ||
self({ content, renderer }): string { | ||
return renderSelf({ content, renderer }); | ||
}, | ||
additionalContent({ content, model, renderer }) { | ||
return ( | ||
content + | ||
renderer.renderBlock([ | ||
`public function jsonSerialize(): mixed`, | ||
'{', | ||
renderer.indent( | ||
renderer.renderBlock([ | ||
'return match($this) {', | ||
renderer.indent( | ||
renderer.renderBlock( | ||
Object.values(model.values).map( | ||
(value) => `self::${value.key} => ${value.value},` | ||
) | ||
) | ||
), | ||
'};' | ||
]) | ||
), | ||
'}' | ||
]) | ||
); | ||
} | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,2 @@ | ||
export * from './DescriptionPreset'; | ||
export * from './JsonSerializablePreset'; |
53 changes: 53 additions & 0 deletions
53
test/generators/php/presets/JsonSerializablePreset.spec.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
import { PHP_JSON_SERIALIZABLE_PRESET, PhpGenerator } from '../../../../src'; | ||
|
||
describe('PHP_JSON_SERIALIZABLE_PRESET', () => { | ||
let generator: PhpGenerator; | ||
beforeEach(() => { | ||
generator = new PhpGenerator({ | ||
presets: [PHP_JSON_SERIALIZABLE_PRESET] | ||
}); | ||
}); | ||
|
||
test('should render jsonSerialize method for class', async () => { | ||
const doc = { | ||
$id: 'Clazz', | ||
type: 'object', | ||
properties: { | ||
prop: { | ||
type: 'string' | ||
}, | ||
'prop-with-dash': { | ||
type: 'string' | ||
} | ||
} | ||
}; | ||
|
||
const models = await generator.generate(doc); | ||
expect(models).toHaveLength(1); | ||
expect(models[0].result).toMatchSnapshot(); | ||
}); | ||
|
||
test('should render jsonSerialize method for enum', async () => { | ||
const doc = { | ||
$id: 'Enumm', | ||
type: 'enum', | ||
enum: ['value-A', 'value-B'] | ||
}; | ||
|
||
const models = await generator.generate(doc); | ||
expect(models).toHaveLength(1); | ||
expect(models[0].result).toMatchSnapshot(); | ||
}); | ||
|
||
test('should render jsonSerialize method for enum with mixed types', async () => { | ||
const doc = { | ||
$id: 'Enumm', | ||
type: 'enum', | ||
enum: [1, 'B'] | ||
}; | ||
|
||
const models = await generator.generate(doc); | ||
expect(models).toHaveLength(1); | ||
expect(models[0].result).toMatchSnapshot(); | ||
}); | ||
}); |
63 changes: 63 additions & 0 deletions
63
test/generators/php/presets/__snapshots__/JsonSerializablePreset.spec.ts.snap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
// Jest Snapshot v1, https://goo.gl/fbAQLP | ||
|
||
exports[`PHP_JSON_SERIALIZABLE_PRESET should render jsonSerialize method for class 1`] = ` | ||
"final class Clazz implements \\\\JsonSerializable | ||
{ | ||
private ?string $prop; | ||
private ?string $propMinusWithMinusDash; | ||
private mixed $additionalProperties; | ||
public function getProp(): ?string { return $this->prop; } | ||
public function setProp(?string $prop): void { $this->prop = $prop; } | ||
public function getPropMinusWithMinusDash(): ?string { return $this->propMinusWithMinusDash; } | ||
public function setPropMinusWithMinusDash(?string $propMinusWithMinusDash): void { $this->propMinusWithMinusDash = $propMinusWithMinusDash; } | ||
public function getAdditionalProperties(): mixed { return $this->additionalProperties; } | ||
public function setAdditionalProperties(mixed $additionalProperties): void { $this->additionalProperties = $additionalProperties; } | ||
public function jsonSerialize(): array | ||
{ | ||
return [ | ||
'prop' => $this->prop, | ||
'prop-with-dash' => $this->propMinusWithMinusDash, | ||
...$this->additionalProperties, | ||
]; | ||
} | ||
} | ||
" | ||
`; | ||
exports[`PHP_JSON_SERIALIZABLE_PRESET should render jsonSerialize method for enum 1`] = ` | ||
"enum Enumm implements \\\\JsonSerializable | ||
{ | ||
case VALUE_MINUS_A; | ||
case VALUE_MINUS_B; | ||
public function jsonSerialize(): mixed | ||
{ | ||
return match($this) { | ||
self::VALUE_MINUS_A => \\"value-A\\", | ||
self::VALUE_MINUS_B => \\"value-B\\", | ||
}; | ||
} | ||
} | ||
" | ||
`; | ||
exports[`PHP_JSON_SERIALIZABLE_PRESET should render jsonSerialize method for enum with mixed types 1`] = ` | ||
"enum Enumm implements \\\\JsonSerializable | ||
{ | ||
case NUMBER_1; | ||
case B; | ||
public function jsonSerialize(): mixed | ||
{ | ||
return match($this) { | ||
self::NUMBER_1 => 1, | ||
self::B => \\"B\\", | ||
}; | ||
} | ||
} | ||
" | ||
`; |