Skip to content

Fix issue #70 #71

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace PHPModelGenerator\PropertyProcessor\ComposedValue;

use PHPModelGenerator\Exception\SchemaException;
use PHPModelGenerator\Model\MethodInterface;
use PHPModelGenerator\Model\Property\CompositionPropertyDecorator;
use PHPModelGenerator\Model\Property\Property;
use PHPModelGenerator\Model\Property\PropertyInterface;
Expand Down Expand Up @@ -117,6 +118,10 @@ function () use (&$resolvedCompositions, $property, $compositionProperties, $pro
),
100
);

if (!$this->schema->hasMethod('_getModifiedValues')) {
$this->addGetModifiedValuesMethodToSchema($compositionProperties);
}
}

/**
Expand Down Expand Up @@ -339,6 +344,64 @@ function () use ($property, $mergedPropertySchema): void {
}
}

/**
* Add a method to the schema to gather values from a nested object which are modified. This is required to adopt
* filter changes to the values which are passed into a merged property
*
* @param CompositionPropertyDecorator[] $compositionProperties
*/
private function addGetModifiedValuesMethodToSchema(array $compositionProperties): void
{
$this->schema->addMethod('_getModifiedValues', new class ($compositionProperties) implements MethodInterface {
/** @var CompositionPropertyDecorator[] $compositionProperties */
private $compositionProperties;

public function __construct(array $compositionProperties)
{
$this->compositionProperties = $compositionProperties;
}

public function getCode(): string
{
$defaultValueMap = [];
$propertyAccessors = [];
foreach ($this->compositionProperties as $compositionProperty) {
if (!$compositionProperty->getNestedSchema()) {
continue;
}

foreach ($compositionProperty->getNestedSchema()->getProperties() as $property) {
$propertyAccessors[$property->getName()] = 'get' . ucfirst($property->getAttribute());

if ($property->getDefaultValue() !== null) {
$defaultValueMap[] = $property->getName();
}
}
}

return sprintf('
private function _getModifiedValues(array $originalModelData, object $nestedCompositionObject): array {
$modifiedValues = [];
$defaultValueMap = %s;

foreach (%s as $key => $accessor) {
if ((isset($originalModelData[$key]) || in_array($key, $defaultValueMap))
&& method_exists($nestedCompositionObject, $accessor)
&& ($modifiedValue = $nestedCompositionObject->$accessor()) !== ($originalModelData[$key] ?? !$modifiedValue)
) {
$modifiedValues[$key] = $modifiedValue;
}
}

return $modifiedValues;
}',
var_export($defaultValueMap, true),
var_export($propertyAccessors, true)
);
}
});
}

/**
* @param int $composedElements The amount of elements which are composed together
*
Expand Down
2 changes: 1 addition & 1 deletion src/Templates/Model.phptpl
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ declare(strict_types = 1);
{% if schema.getDescription() %} * {{ schema.getDescription() }}
*{% endif %}
* This is an auto-implemented class implemented by the php-json-schema-model-generator.
* If you need to implement something in this class use inheritance. Else you will loose your changes if the classes
* If you need to implement something in this class use inheritance. Else you will lose your changes if the classes
* are re-generated.
*/
class {{ class }} {% if schema.getInterfaces() %}implements {{ viewHelper.joinClassNames(schema.getInterfaces()) }}{% endif %}
Expand Down
8 changes: 8 additions & 0 deletions src/Templates/Validator/ComposedItem.phptpl
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
$validatorComponentIndex = 0;
$originalModelData = $value;
$proposedValue = null;
$modifiedValues = [];

{% if not generatorConfiguration.isImmutable() %}
$originalPropertyValidationState = $this->_propertyValidationState ?? [];
Expand Down Expand Up @@ -90,6 +91,9 @@
$proposedValue = $proposedValue ?? $value;
{% endif %}

if (is_object($value)) {
$modifiedValues = array_merge($modifiedValues, $this->_getModifiedValues($originalModelData, $value));
}
{% if not generatorConfiguration.isImmutable() %}
{% if not generatorConfiguration.collectErrors() %}
if (isset($validatorIndex)) {
Expand Down Expand Up @@ -118,6 +122,10 @@

{% if mergedProperty %}
if (is_object($proposedValue)) {
if ($modifiedValues) {
$value = array_merge($value, $modifiedValues);
}

{{ viewHelper.resolvePropertyDecorator(mergedProperty) }}
} else {
$value = $proposedValue;
Expand Down
74 changes: 74 additions & 0 deletions tests/Issues/Issue/Issue70Test.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

declare(strict_types=1);

namespace PHPModelGenerator\Tests\Issues\Issue;

use PHPModelGenerator\Filter\TransformingFilterInterface;
use PHPModelGenerator\Model\GeneratorConfiguration;
use PHPModelGenerator\Tests\Issues\AbstractIssueTest;

class Issue70Test extends AbstractIssueTest
{
/**
* @dataProvider validInputDataProvider
*/
public function testValidInput(string $filter, array $input, $expectedOutput): void
{
$className = $this->generateClassFromFileTemplate(
'filterInCompositionInArray.json',
[$filter],
(new GeneratorConfiguration())->addFilter($this->getFilter())
);

$object = new $className($input);

$this->assertCount(1, $object->getItems());
$this->assertSame('Hello', $object->getItems()[0]->getTitle());
$this->assertSame($expectedOutput, $object->getItems()[0]->getProperty());
}

public function validInputDataProvider(): array
{
return [
'basic filter - default value' => ['trim', ['items' => [['title' => 'Hello']]], 'now'],
'basic filter - custom value - not modified' => ['trim', ['items' => [['title' => 'Hello', 'property' => 'later']]], 'later'],
'basic filter - custom value - modified' => ['trim', ['items' => [['title' => 'Hello', 'property' => ' later ']]], 'later'],
'basic filter - null' => ['trim', ['items' => [['title' => 'Hello', 'property' => null]]], null],
'transforming filter - default value' => ['countChars', ['items' => [['title' => 'Hello']]], 3],
'transforming filter - transformed value' => ['countChars', ['items' => [['title' => 'Hello', 'property' => 5]]], 5],
'transforming filter - custom value' => ['countChars', ['items' => [['title' => 'Hello', 'property' => 'Hello World']]], 11],
'transforming filter - null' => ['countChars', ['items' => [['title' => 'Hello', 'property' => null]]], null],
];
}

public function getFilter(): TransformingFilterInterface
{
return new class () implements TransformingFilterInterface {
public function getAcceptedTypes(): array
{
return ['string', 'null'];
}

public function getToken(): string
{
return 'countChars';
}

public function getFilter(): array
{
return [Issue70Test::class, 'filter'];
}

public function getSerializer(): array
{
return [Issue70Test::class, 'filter'];
}
};
}

public static function filter(?string $input): ?int
{
return $input === null ? null : strlen($input);
}
}
33 changes: 33 additions & 0 deletions tests/Schema/Issues/70/filterInCompositionInArray.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"type": "object",
"properties": {
"items": {
"type": "array",
"items":{
"allOf": [
{
"type": "object",
"properties": {
"title": {
"type": "string"
}
},
"required": [
"title"
]
},
{
"type": "object",
"properties": {
"property": {
"type": "string",
"filter": "%s",
"default": "now"
}
}
}
]
}
}
}
}