Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[JsonEncoder] Remove chunk size definition #59254

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
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 @@ -32,7 +32,6 @@
tagged_locator('json_encoder.normalizer'),
service('json_encoder.encode.property_metadata_loader'),
param('.json_encoder.encoders_dir'),
false,
])
->set('json_encoder.decoder', JsonDecoder::class)
->args([
Expand Down Expand Up @@ -113,7 +112,6 @@
service('json_encoder.decode.property_metadata_loader'),
param('.json_encoder.encoders_dir'),
param('.json_encoder.decoders_dir'),
false,
service('logger')->ignoreOnInvalid(),
])
->tag('kernel.cache_warmer')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,9 @@ public function __construct(
PropertyMetadataLoaderInterface $decodePropertyMetadataLoader,
string $encodersDir,
string $decodersDir,
bool $forceEncodeChunks = false,
private LoggerInterface $logger = new NullLogger(),
) {
$this->encoderGenerator = new EncoderGenerator($encodePropertyMetadataLoader, $encodersDir, $forceEncodeChunks);
$this->encoderGenerator = new EncoderGenerator($encodePropertyMetadataLoader, $encodersDir);
$this->decoderGenerator = new DecoderGenerator($decodePropertyMetadataLoader, $decodersDir);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ public function __construct(
private DataAccessorInterface $accessor,
private ObjectType $type,
private array $properties,
private bool $transformed,
) {
}

Expand All @@ -51,9 +50,4 @@ public function getProperties(): array
{
return $this->properties;
}

public function isTransformed(): bool
{
return $this->transformed;
}
}
20 changes: 3 additions & 17 deletions 20 src/Symfony/Component/JsonEncoder/Encode/EncoderGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
use Symfony\Component\JsonEncoder\Exception\MaxDepthException;
use Symfony\Component\JsonEncoder\Exception\RuntimeException;
use Symfony\Component\JsonEncoder\Exception\UnsupportedException;
use Symfony\Component\JsonEncoder\Mapping\PropertyMetadata;
use Symfony\Component\JsonEncoder\Mapping\PropertyMetadataLoaderInterface;
use Symfony\Component\TypeInfo\Type;
use Symfony\Component\TypeInfo\Type\BackedEnumType;
Expand All @@ -57,13 +56,9 @@ final class EncoderGenerator
private ?PrettyPrinter $phpPrinter = null;
private ?Filesystem $fs = null;

/**
* @param bool $forceEncodeChunks enforces chunking the JSON string even if a simple `json_encode` is enough
*/
public function __construct(
private PropertyMetadataLoaderInterface $propertyMetadataLoader,
private string $encodersDir,
private bool $forceEncodeChunks,
) {
}

Expand All @@ -79,7 +74,7 @@ public function generate(Type $type, array $options = []): string
return $path;
}

$this->phpAstBuilder ??= new PhpAstBuilder($this->forceEncodeChunks);
$this->phpAstBuilder ??= new PhpAstBuilder();
$this->phpOptimizer ??= new PhpOptimizer();
$this->phpPrinter ??= new Standard(['phpVersion' => PhpVersion::fromComponents(8, 2)]);
$this->fs ??= new Filesystem();
Expand Down Expand Up @@ -110,7 +105,7 @@ public function generate(Type $type, array $options = []): string

private function getPath(Type $type): string
{
return \sprintf('%s%s%s.json%s.php', $this->encodersDir, \DIRECTORY_SEPARATOR, hash('xxh128', (string) $type), $this->forceEncodeChunks ? '.stream' : '');
return \sprintf('%s%s%s.json.php', $this->encodersDir, \DIRECTORY_SEPARATOR, hash('xxh128', (string) $type));
}

/**
Expand Down Expand Up @@ -142,7 +137,6 @@ private function createDataModel(Type $type, DataAccessorInterface $accessor, ar
if ($type instanceof ObjectType && !$type instanceof EnumType) {
++$context['depth'];

$transformed = false;
$className = $type->getClassName();
$propertiesMetadata = $this->propertyMetadataLoader->load($className, $options, ['original_type' => $type] + $context);

Expand All @@ -152,20 +146,12 @@ private function createDataModel(Type $type, DataAccessorInterface $accessor, ar
throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
}

if (\count($classReflection->getProperties()) !== \count($propertiesMetadata)
|| array_values(array_map(fn (PropertyMetadata $m): string => $m->getName(), $propertiesMetadata)) !== array_keys($propertiesMetadata)
) {
$transformed = true;
}

$propertiesNodes = [];

foreach ($propertiesMetadata as $encodedName => $propertyMetadata) {
$propertyAccessor = new PropertyDataAccessor($accessor, $propertyMetadata->getName());

foreach ($propertyMetadata->getNormalizers() as $normalizer) {
$transformed = true;

if (\is_string($normalizer)) {
$normalizerServiceAccessor = new FunctionDataAccessor('get', [new ScalarDataAccessor($normalizer)], new VariableDataAccessor('normalizers'));
$propertyAccessor = new FunctionDataAccessor('normalize', [$propertyAccessor, new VariableDataAccessor('options')], $normalizerServiceAccessor);
Expand All @@ -190,7 +176,7 @@ private function createDataModel(Type $type, DataAccessorInterface $accessor, ar
$propertiesNodes[$encodedName] = $this->createDataModel($propertyMetadata->getType(), $propertyAccessor, $options, $context);
}

return new ObjectNode($accessor, $type, $propertiesNodes, $transformed);
return new ObjectNode($accessor, $type, $propertiesNodes);
}

if ($type instanceof CollectionType) {
Expand Down
18 changes: 4 additions & 14 deletions 18 src/Symfony/Component/JsonEncoder/Encode/PhpAstBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,8 @@ final class PhpAstBuilder
{
private BuilderFactory $builder;

public function __construct(
private bool $forceEncodeChunks = false,
) {
public function __construct()
{
$this->builder = new BuilderFactory();
}

Expand Down Expand Up @@ -103,7 +102,7 @@ private function buildClosureStatements(DataModelNodeInterface $dataModelNode, a
];
}

if (!$this->forceEncodeChunks && $this->nodeOnlyNeedsEncode($dataModelNode)) {
if ($this->nodeOnlyNeedsEncode($dataModelNode)) {
return [
new Expression(new Yield_($this->encodeValue($accessor))),
];
Expand Down Expand Up @@ -276,21 +275,12 @@ private function nodeOnlyNeedsEncode(DataModelNodeInterface $node, int $nestingL
return $this->nodeOnlyNeedsEncode($node->getItemNode(), $nestingLevel + 1);
}

if ($node instanceof ObjectNode && !$node->isTransformed()) {
foreach ($node->getProperties() as $property) {
if (!$this->nodeOnlyNeedsEncode($property, $nestingLevel + 1)) {
return false;
}
}

return true;
}

if ($node instanceof ScalarNode) {
$type = $node->getType();

// "null" will be written directly using the "null" string
// "bool" will be written directly using the "true" or "false" string
// but it must not prevent any json_encode if nested
if ($type->isIdentifiedBy(TypeIdentifier::NULL) || $type->isIdentifiedBy(TypeIdentifier::BOOL)) {
return $nestingLevel > 0;
}
Expand Down
11 changes: 3 additions & 8 deletions 11 src/Symfony/Component/JsonEncoder/JsonEncoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,12 @@ final class JsonEncoder implements EncoderInterface
{
private EncoderGenerator $encoderGenerator;

/**
* @param bool $forceEncodeChunks enforces chunking the JSON string even if a simple `json_encode` is enough
*/
public function __construct(
private ContainerInterface $normalizers,
PropertyMetadataLoaderInterface $propertyMetadataLoader,
string $encodersDir,
bool $forceEncodeChunks = false,
) {
$this->encoderGenerator = new EncoderGenerator($propertyMetadataLoader, $encodersDir, $forceEncodeChunks);
$this->encoderGenerator = new EncoderGenerator($propertyMetadataLoader, $encodersDir);
}

public function encode(mixed $data, Type $type, array $options = []): \Traversable&\Stringable
Expand All @@ -58,9 +54,8 @@ public function encode(mixed $data, Type $type, array $options = []): \Traversab

/**
* @param array<string, NormalizerInterface> $normalizers
* @param bool $forceEncodeChunks enforces chunking the JSON string even if a simple `json_encode` is enough
*/
public static function create(array $normalizers = [], ?string $encodersDir = null, bool $forceEncodeChunks = false): self
public static function create(array $normalizers = [], ?string $encodersDir = null): self
{
$encodersDir ??= sys_get_temp_dir().'/json_encoder/encoder';
$normalizers += [
Expand Down Expand Up @@ -97,6 +92,6 @@ public function get(string $id): NormalizerInterface
$typeContextFactory,
);

return new self($normalizersContainer, $propertyMetadataLoader, $encodersDir, $forceEncodeChunks);
return new self($normalizersContainer, $propertyMetadataLoader, $encodersDir);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public function testSortNodesOnCreation()
{
$composite = new CompositeNode(new VariableDataAccessor('data'), [
$scalar = new ScalarNode(new VariableDataAccessor('data'), Type::int()),
$object = new ObjectNode(new VariableDataAccessor('data'), Type::object(self::class), [], false),
$object = new ObjectNode(new VariableDataAccessor('data'), Type::object(self::class), []),
$collection = new CollectionNode(new VariableDataAccessor('data'), Type::list(), new ScalarNode(new VariableDataAccessor('data'), Type::int())),
]);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,19 +66,12 @@ public function testGeneratedEncoder(string $fixture, Type $type)
new TypeContextFactory(new StringTypeResolver()),
);

$generator = new EncoderGenerator($propertyMetadataLoader, $this->encodersDir, forceEncodeChunks: false);
$generator = new EncoderGenerator($propertyMetadataLoader, $this->encodersDir);

$this->assertStringEqualsFile(
\sprintf('%s/Fixtures/encoder/%s.php', \dirname(__DIR__), $fixture),
file_get_contents($generator->generate($type)),
);

$generator = new EncoderGenerator($propertyMetadataLoader, $this->encodersDir, forceEncodeChunks: true);

$this->assertStringEqualsFile(
\sprintf('%s/Fixtures/encoder/%s.stream.php', \dirname(__DIR__), $fixture),
file_get_contents($generator->generate($type)),
);
}

/**
Expand Down Expand Up @@ -117,7 +110,7 @@ public static function generatedEncoderDataProvider(): iterable

public function testDoNotSupportIntersectionType()
{
$generator = new EncoderGenerator(new PropertyMetadataLoader(TypeResolver::create()), $this->encodersDir, false);
$generator = new EncoderGenerator(new PropertyMetadataLoader(TypeResolver::create()), $this->encodersDir);

$this->expectException(UnsupportedException::class);
$this->expectExceptionMessage('"Stringable&Traversable" type is not supported.');
Expand All @@ -127,7 +120,7 @@ public function testDoNotSupportIntersectionType()

public function testDoNotSupportEnumType()
{
$generator = new EncoderGenerator(new PropertyMetadataLoader(TypeResolver::create()), $this->encodersDir, false);
$generator = new EncoderGenerator(new PropertyMetadataLoader(TypeResolver::create()), $this->encodersDir);

$this->expectException(UnsupportedException::class);
$this->expectExceptionMessage(\sprintf('"%s" type is not supported.', DummyEnum::class));
Expand Down

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.