Skip to content

Commit

Permalink
Do not remove empty default values for string and array respectively (#…
Browse files Browse the repository at this point in the history
…1028)

* Do not remove empty string and empty array as default values for string and array respectively
* Save flag initial value for field was eliminated by optimization
* Add test case
* Mark test as correct

Signed-off-by: dsolomennikov <dsolomennikov@>
  • Loading branch information
soloth authored Aug 15, 2024
1 parent 49415b2 commit c265c18
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 1 deletion.
2 changes: 1 addition & 1 deletion compiler/data/kphp-json-tags.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,7 @@ FieldJsonSettings merge_and_inherit_json_tags(const ClassMemberInstanceField &fi

// for 'public int $id;' — no default and non-nullable type — set 'required' so that decode() would fire unless exists
// it could be overridden with `@kphp-json required = false`
if (field.type_hint && !field.var->init_val && !does_type_hint_allow_null(field.type_hint)) {
if (field.type_hint && !field.var->init_val && !field.var->had_user_assigned_val && !does_type_hint_allow_null(field.type_hint)) {
s.required = true;
}

Expand Down
1 change: 1 addition & 0 deletions compiler/data/var-data.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ class VarData {
std::string name;
tinf::VarNode tinf_node;
VertexPtr init_val;
bool had_user_assigned_val = false;
FunctionPtr holder_func;
ClassPtr class_id;
std::unordered_set<VarPtr> *bad_vars = nullptr;
Expand Down
1 change: 1 addition & 0 deletions compiler/pipes/optimization.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,7 @@ void OptimizationPass::on_finish() {

if (can_init_value_be_removed(class_field.var->init_val, class_field.var)) {
class_field.var->init_val = {};
class_field.var->had_user_assigned_val = true;
} else {
explicit_cast_array_type(class_field.var->init_val, tinf::get_type(class_field.var));
}
Expand Down
23 changes: 23 additions & 0 deletions tests/phpt/json/38_optimized_init_val.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
@ok
<?php

class User {
public string $name = '';
public string $password = '';
}

function test_optimized_init_value(): void {
$raw = '{"name": "user"}';

$user = JsonEncoder::decode($raw, User::class);

$error = JsonEncoder::getLastError();
if (!empty($error)) {
echo "Error: " . $error;
exit();
}

var_dump(instance_to_array($user));
}

test_optimized_init_value();

0 comments on commit c265c18

Please sign in to comment.