Repository navigation
Expand file tree
/
Copy pathinvoice.php
More file actions
executable file
·63 lines (50 loc) · 1.83 KB
/
Copy pathinvoice.php
File metadata and controls
executable file
·63 lines (50 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env php
<?php
declare(strict_types=1);
/**
* Runs the runtime directly, with no protoc step — matches the "Using
* the runtime directly" example in the README. Equivalent to:
*
* syntax = "proto2";
* message Invoice {
* required int32 id = 1;
* optional string customer = 2;
* repeated int32 line_totals = 3 [packed = true];
* }
*
* Usage: php example/invoice.php
*/
namespace Aaronlow\Proto2Php\Example;
use Aaronlow\Proto2Php\Runtime\Field;
use Aaronlow\Proto2Php\Runtime\FieldType;
use Aaronlow\Proto2Php\Runtime\Label;
use Aaronlow\Proto2Php\Runtime\Message;
use function strlen;
use const JSON_PRETTY_PRINT;
require __DIR__ . '/../vendor/autoload.php';
final class Invoice extends Message
{
public static function fields(): array
{
return [
new Field(1, 'id', FieldType::INT32, Label::REQUIRED),
new Field(2, 'customer', FieldType::STRING, Label::OPTIONAL),
new Field(3, 'line_totals', FieldType::INT32, Label::REPEATED, packed: true),
];
}
}
$invoice = new Invoice()
->set(1, 1001)
->set(2, 'Jane Doe')
->add(3, 1500)
->add(3, 2200);
$bytes = $invoice->serializeToString();
printf("Serialized to %d bytes: %s\n", strlen($bytes), bin2hex($bytes));
// isInitialized() checks required fields recursively; false here shows
// what an incomplete message looks like before we build the real one.
$incomplete = new Invoice()->set(2, 'no id set');
printf("Incomplete invoice initialized? %s\n", $incomplete->isInitialized() ? 'yes' : 'no');
printf("Complete invoice initialized? %s\n", $invoice->isInitialized() ? 'yes' : 'no');
$parsed = Invoice::parseFromString($bytes);
printf("Round-tripped customer: %s (has: %s)\n", $parsed->get(2), $parsed->has(2) ? 'true' : 'false');
echo json_encode($parsed->toArray(), JSON_PRETTY_PRINT) . "\n";