xref: /PHP-8.2/Zend/tests/enum/json_encode.phpt (revision 2145f80d)
1--TEST--
2Enum in json_encode
3--FILE--
4<?php
5
6enum Foo {
7    case Bar;
8}
9
10enum IntFoo: int {
11    case Bar = 0;
12}
13
14enum StringFoo: string {
15    case Bar = 'Bar';
16}
17
18enum CustomFoo implements JsonSerializable {
19    case Bar;
20
21    public function jsonSerialize(): mixed {
22        return 'Custom ' . $this->name;
23    }
24}
25
26function test($value) {
27    var_dump(json_encode($value));
28    echo json_last_error_msg() . "\n";
29    if (json_last_error() !== JSON_ERROR_NONE) {
30        echo json_last_error() . ' === '  . JSON_ERROR_NON_BACKED_ENUM . ":\n";
31        var_dump(json_last_error() === JSON_ERROR_NON_BACKED_ENUM);
32    }
33
34    try {
35        var_dump(json_encode($value, JSON_THROW_ON_ERROR));
36        echo json_last_error_msg() . "\n";
37    } catch (Exception $e) {
38        echo get_class($e) . ': ' . $e->getMessage() . "\n";
39    }
40}
41
42test(Foo::Bar);
43test(IntFoo::Bar);
44test(StringFoo::Bar);
45test(CustomFoo::Bar);
46
47?>
48--EXPECT--
49bool(false)
50Non-backed enums have no default serialization
5111 === 11:
52bool(true)
53JsonException: Non-backed enums have no default serialization
54string(1) "0"
55No error
56string(1) "0"
57No error
58string(5) ""Bar""
59No error
60string(5) ""Bar""
61No error
62string(12) ""Custom Bar""
63No error
64string(12) ""Custom Bar""
65No error
66