spikard-cli 0.15.6-rc.16

Command-line interface for building and validating Spikard applications
Documentation
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! PHP Protobuf code generator.
//!
//! This generator produces type-safe PHP code for Protobuf message and service definitions.
//! Generated code uses PHP 8.1+ typed properties and PHPStan-compatible type annotations
//! with the google/protobuf library.

use super::ProtobufGenerator;
use super::base::{escape_string, map_proto_type_to_language, sanitize_identifier, to_camel_case};
use crate::codegen::protobuf::spec_parser::{FieldLabel, MessageDef, ProtobufSchema, ServiceDef};
use anyhow::Result;

/// PHP Protobuf code generator
#[derive(Default, Debug, Clone, Copy)]
#[allow(dead_code)]
pub struct PhpProtobufGenerator;

impl ProtobufGenerator for PhpProtobufGenerator {
    fn generate_complete(&self, schema: &ProtobufSchema) -> Result<String> {
        let mut code = String::new();
        let namespace = php_namespace(schema.package.as_deref());
        let has_messages = !schema.messages.is_empty() || !schema.enums.is_empty();
        let has_services = !schema.services.is_empty();

        code.push_str("<?php\n");
        code.push_str("// DO NOT EDIT - Auto-generated by Spikard CLI\n");
        code.push_str("//\n");
        code.push_str("// This file was automatically generated from your Protobuf schema.\n");
        code.push_str("// Any manual changes will be overwritten on the next generation.\n\n");
        code.push_str("declare(strict_types=1);\n\n");
        code.push_str(&format!("namespace {namespace};\n\n"));

        if has_messages {
            code.push_str("use Google\\Protobuf\\Internal\\Message;\n");
        }
        if has_services {
            code.push_str("use RuntimeException;\n");
        }
        if has_messages || has_services {
            code.push('\n');
        }

        for message in schema.messages.values() {
            code.push_str(&self.generate_message_class(message));
            code.push_str("\n\n");
        }

        for enum_def in schema.enums.values() {
            code.push_str(&self.generate_enum_class(enum_def));
            code.push_str("\n\n");
        }

        if schema.services.is_empty() {
            code.push_str("// No services defined in this schema.\n");
        } else {
            for service in schema.services.values() {
                code.push_str(&self.generate_service_class(service));
                code.push_str("\n\n");
            }
        }

        Ok(code.trim_end().to_string() + "\n")
    }

    fn generate_messages(&self, schema: &ProtobufSchema) -> Result<String> {
        let mut code = String::new();
        let namespace = php_namespace(schema.package.as_deref());

        // File header
        code.push_str("<?php\n");
        code.push_str("// DO NOT EDIT - Auto-generated by Spikard CLI\n");
        code.push_str("//\n");
        code.push_str("// This file was automatically generated from your Protobuf schema.\n");
        code.push_str("// Any manual changes will be overwritten on the next generation.\n\n");

        code.push_str("declare(strict_types=1);\n\n");

        // Namespace
        code.push_str(&format!("namespace {namespace};\n\n"));

        // Imports
        code.push_str("use Google\\Protobuf\\Internal\\Message;\n\n");

        // Generate message definitions
        for message in schema.messages.values() {
            code.push_str(&self.generate_message_class(message));
            code.push_str("\n\n");
        }

        // Generate enum definitions
        for enum_def in schema.enums.values() {
            code.push_str(&self.generate_enum_class(enum_def));
            code.push_str("\n\n");
        }

        Ok(code.trim_end().to_string() + "\n")
    }

    fn generate_services(&self, schema: &ProtobufSchema) -> Result<String> {
        let mut code = String::new();
        let namespace = php_namespace(schema.package.as_deref());

        // File header
        code.push_str("<?php\n");
        code.push_str("// DO NOT EDIT - Auto-generated by Spikard CLI\n");
        code.push_str("//\n");
        code.push_str("// This file was automatically generated from your Protobuf schema.\n");
        code.push_str("// Any manual changes will be overwritten on the next generation.\n\n");

        code.push_str("declare(strict_types=1);\n\n");

        // Namespace
        code.push_str(&format!("namespace {namespace};\n\n"));

        // Imports
        code.push_str("use RuntimeException;\n\n");

        // Generate service definitions
        if schema.services.is_empty() {
            code.push_str("// No services defined in this schema.\n");
        } else {
            for service in schema.services.values() {
                code.push_str(&self.generate_service_class(service));
                code.push_str("\n\n");
            }
        }

        Ok(code.trim_end().to_string() + "\n")
    }
}

fn php_namespace(package: Option<&str>) -> String {
    package.unwrap_or("Protobuf").replace('.', "\\")
}

impl PhpProtobufGenerator {
    fn phpdoc_field_type(&self, field: &crate::codegen::protobuf::spec_parser::FieldDef) -> String {
        let base_type = map_proto_type_to_language(&field.field_type, "php", false, false);

        match field.label {
            FieldLabel::Repeated => format!("list<{base_type}>"),
            FieldLabel::Optional => format!("{base_type}|null"),
            _ => base_type,
        }
    }

    /// Generate a message class definition
    #[allow(dead_code)]
    fn generate_message_class(&self, message: &MessageDef) -> String {
        let mut code = String::new();

        // Class definition
        code.push_str(&format!("class {} extends Message\n", message.name));
        code.push_str("{\n");

        // Docstring
        if let Some(desc) = &message.description {
            code.push_str(&format!("    /**\n     * {}\n     */\n", escape_string(desc, "php")));
        } else {
            code.push_str("    /**\n     * Generated protocol buffer message.\n     */\n");
        }

        if message.fields.is_empty() {
            code.push_str("}\n");
        } else {
            // Add typed properties
            for field in &message.fields {
                // Field comment if available
                if let Some(desc) = &field.description {
                    code.push_str(&format!("    /**\n     * {}\n     */\n", escape_string(desc, "php")));
                }

                let field_name = sanitize_identifier(&field.name, "php");
                let is_optional = field.label == FieldLabel::Optional;
                let is_repeated = field.label == FieldLabel::Repeated;

                let field_type = map_proto_type_to_language(&field.field_type, "php", is_optional, is_repeated);
                let phpdoc_type = self.phpdoc_field_type(field);

                // Default value based on type
                let default_val = if is_repeated {
                    "[]".to_string()
                } else if is_optional {
                    "null".to_string()
                } else if matches!(
                    field.field_type,
                    crate::codegen::protobuf::spec_parser::ProtoType::String
                        | crate::codegen::protobuf::spec_parser::ProtoType::Bytes
                ) {
                    "''".to_string()
                } else if matches!(field.field_type, crate::codegen::protobuf::spec_parser::ProtoType::Bool) {
                    "false".to_string()
                } else {
                    "0".to_string()
                };

                code.push_str(&format!("    /** @var {phpdoc_type} */\n"));
                code.push_str(&format!("    protected {field_type} ${field_name} = {default_val};\n"));
            }

            code.push_str("}\n");
        }

        code
    }

    /// Generate an enum class definition
    #[allow(dead_code)]
    fn generate_enum_class(&self, enum_def: &crate::codegen::protobuf::spec_parser::EnumDef) -> String {
        let mut code = String::new();

        code.push_str(&format!("class {} extends Message\n", enum_def.name));
        code.push_str("{\n");

        // Docstring
        if let Some(desc) = &enum_def.description {
            code.push_str(&format!("    /**\n     * {}\n     */\n", escape_string(desc, "php")));
        } else {
            code.push_str("    /**\n     * Protobuf enum type.\n     */\n");
        }

        if enum_def.values.is_empty() {
            code.push_str("}\n");
        } else {
            for value in &enum_def.values {
                if let Some(desc) = &value.description {
                    code.push_str(&format!("    /** {} */\n", escape_string(desc, "php")));
                }
                code.push_str(&format!(
                    "    const {} = {};\n",
                    value.name.to_uppercase(),
                    value.number
                ));
            }
            code.push_str("}\n");
        }

        code
    }

    /// Generate a service class definition (server interface)
    #[allow(dead_code)]
    fn generate_service_class(&self, service: &ServiceDef) -> String {
        let mut code = String::new();

        // Service class
        code.push_str(&format!("class {}\n", service.name));
        code.push_str("{\n");

        // Docstring
        if let Some(desc) = &service.description {
            code.push_str(&format!(
                "    /**\n     * Server handler interface for {}.\n     * {}\n     */\n",
                service.name,
                escape_string(desc, "php")
            ));
        } else {
            code.push_str(&format!(
                "    /**\n     * Server handler interface for {}.\n     */\n",
                service.name
            ));
        }

        if service.methods.is_empty() {
            code.push_str("}\n");
        } else {
            for method in &service.methods {
                code.push('\n');

                // Method docstring
                if let Some(desc) = &method.description {
                    code.push_str(&format!("    /**\n     * {}\n", escape_string(desc, "php")));
                } else {
                    code.push_str("    /**\n");
                }

                // Build method signature
                let sanitized_name = sanitize_identifier(&method.name, "php");
                let method_name = to_camel_case(&sanitized_name);
                let request_type = &method.input_type;
                let response_type = &method.output_type;

                code.push_str(&format!("     * @param {request_type} $request\n"));
                code.push_str(&format!("     * @return {response_type}\n"));
                code.push_str("     */\n");

                // Use fixed parameter name $request to avoid indexing issues
                code.push_str(&format!(
                    "    public function {method_name}({request_type} $request): {response_type}\n"
                ));

                code.push_str("    {\n");
                code.push_str("        throw new RuntimeException('Not implemented');\n");
                code.push_str("    }\n");
            }

            code.push_str("}\n");
        }

        code
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::codegen::protobuf::spec_parser::{FieldDef, FieldLabel, MessageDef, ProtoType};

    #[test]
    fn test_generate_simple_message() {
        let message = MessageDef {
            name: "User".to_string(),
            fields: vec![
                FieldDef {
                    name: "id".to_string(),
                    number: 1,
                    field_type: ProtoType::String,
                    label: FieldLabel::None,
                    default_value: None,
                    description: None,
                },
                FieldDef {
                    name: "name".to_string(),
                    number: 2,
                    field_type: ProtoType::String,
                    label: FieldLabel::None,
                    default_value: None,
                    description: Some("User's full name".to_string()),
                },
            ],
            nested_messages: std::collections::HashMap::new(),
            nested_enums: std::collections::HashMap::new(),
            description: Some("Represents a user".to_string()),
        };

        let generator = PhpProtobufGenerator;
        let code = generator.generate_message_class(&message);

        assert!(code.contains("class User extends Message"));
        assert!(code.contains("Represents a user"));
        assert!(code.contains("protected string $id = ''"));
        assert!(code.contains("protected string $name = ''"));
    }

    #[test]
    fn test_generate_message_with_optional_field() {
        let message = MessageDef {
            name: "User".to_string(),
            fields: vec![FieldDef {
                name: "email".to_string(),
                number: 3,
                field_type: ProtoType::String,
                label: FieldLabel::Optional,
                default_value: None,
                description: None,
            }],
            nested_messages: std::collections::HashMap::new(),
            nested_enums: std::collections::HashMap::new(),
            description: None,
        };

        let generator = PhpProtobufGenerator;
        let code = generator.generate_message_class(&message);

        assert!(code.contains("protected ?string $email = null"));
    }

    #[test]
    fn test_generate_message_with_repeated_field() {
        let message = MessageDef {
            name: "User".to_string(),
            fields: vec![FieldDef {
                name: "tags".to_string(),
                number: 4,
                field_type: ProtoType::String,
                label: FieldLabel::Repeated,
                default_value: None,
                description: None,
            }],
            nested_messages: std::collections::HashMap::new(),
            nested_enums: std::collections::HashMap::new(),
            description: None,
        };

        let generator = PhpProtobufGenerator;
        let code = generator.generate_message_class(&message);

        assert!(code.contains("protected array $tags = []"));
    }

    #[test]
    fn test_generate_typed_properties() {
        let message = MessageDef {
            name: "TestMessage".to_string(),
            fields: vec![
                FieldDef {
                    name: "count".to_string(),
                    number: 1,
                    field_type: ProtoType::Int32,
                    label: FieldLabel::None,
                    default_value: None,
                    description: None,
                },
                FieldDef {
                    name: "enabled".to_string(),
                    number: 2,
                    field_type: ProtoType::Bool,
                    label: FieldLabel::None,
                    default_value: None,
                    description: None,
                },
                FieldDef {
                    name: "value".to_string(),
                    number: 3,
                    field_type: ProtoType::Float,
                    label: FieldLabel::None,
                    default_value: None,
                    description: None,
                },
            ],
            nested_messages: std::collections::HashMap::new(),
            nested_enums: std::collections::HashMap::new(),
            description: None,
        };

        let generator = PhpProtobufGenerator;
        let code = generator.generate_message_class(&message);

        assert!(code.contains("protected int $count = 0"));
        assert!(code.contains("protected bool $enabled = false"));
        assert!(code.contains("protected float $value = 0"));
    }

    #[test]
    fn test_generate_service_class() {
        let service = ServiceDef {
            name: "UserService".to_string(),
            methods: vec![crate::codegen::protobuf::spec_parser::MethodDef {
                name: "get_user".to_string(),
                input_type: "GetUserRequest".to_string(),
                output_type: "User".to_string(),
                input_streaming: false,
                output_streaming: false,
                description: None,
            }],
            description: Some("User service".to_string()),
        };

        let generator = PhpProtobufGenerator;
        let code = generator.generate_service_class(&service);

        assert!(code.contains("class UserService"));
        assert!(code.contains("public function getUser"));
        assert!(code.contains("GetUserRequest"));
        assert!(code.contains("User"));
        assert!(code.contains("RuntimeException"));
    }

    #[test]
    fn test_generate_messages_with_namespace() {
        let schema = ProtobufSchema {
            package: Some("Example\\Api".to_string()),
            messages: vec![(
                "User".to_string(),
                MessageDef {
                    name: "User".to_string(),
                    fields: vec![FieldDef {
                        name: "id".to_string(),
                        number: 1,
                        field_type: ProtoType::String,
                        label: FieldLabel::None,
                        default_value: None,
                        description: None,
                    }],
                    nested_messages: std::collections::HashMap::new(),
                    nested_enums: std::collections::HashMap::new(),
                    description: None,
                },
            )]
            .into_iter()
            .collect(),
            services: std::collections::HashMap::new(),
            enums: std::collections::HashMap::new(),
            imports: vec![],
            syntax: "proto3".to_string(),
            description: None,
        };

        let generator = PhpProtobufGenerator;
        let code = generator
            .generate_messages(&schema)
            .expect("Failed to generate messages");

        assert!(code.contains("<?php"));
        assert!(code.contains("namespace Example\\Api"));
        assert!(code.contains("use Google\\Protobuf\\Internal\\Message"));
        assert!(code.contains("class User extends Message"));
    }

    #[test]
    fn test_generate_services_with_namespace() {
        let schema = ProtobufSchema {
            package: Some("Example\\Service".to_string()),
            messages: std::collections::HashMap::new(),
            services: vec![(
                "UserService".to_string(),
                ServiceDef {
                    name: "UserService".to_string(),
                    methods: vec![],
                    description: None,
                },
            )]
            .into_iter()
            .collect(),
            enums: std::collections::HashMap::new(),
            imports: vec![],
            syntax: "proto3".to_string(),
            description: None,
        };

        let generator = PhpProtobufGenerator;
        let code = generator
            .generate_services(&schema)
            .expect("Failed to generate services");

        assert!(code.contains("<?php"));
        assert!(code.contains("namespace Example\\Service"));
        assert!(code.contains("use RuntimeException"));
    }

    #[test]
    fn test_enum_class_generation() {
        let enum_def = crate::codegen::protobuf::spec_parser::EnumDef {
            name: "Status".to_string(),
            values: vec![
                crate::codegen::protobuf::spec_parser::EnumValue {
                    name: "UNKNOWN".to_string(),
                    number: 0,
                    description: None,
                },
                crate::codegen::protobuf::spec_parser::EnumValue {
                    name: "ACTIVE".to_string(),
                    number: 1,
                    description: Some("Active status".to_string()),
                },
            ],
            description: Some("Status enumeration".to_string()),
        };

        let generator = PhpProtobufGenerator;
        let code = generator.generate_enum_class(&enum_def);

        assert!(code.contains("class Status extends Message"));
        assert!(code.contains("const UNKNOWN = 0"));
        assert!(code.contains("const ACTIVE = 1"));
        assert!(code.contains("Status enumeration"));
    }
}