Skip to content

Commit f5cb3e4

Browse files
committed
handle init function case
Signed-off-by: Robert Landers <landers.robert@gmail.com>
1 parent 5c6a4c3 commit f5cb3e4

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

internal/extgen/gofile.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
_ "embed"
66
"fmt"
77
"path/filepath"
8+
"strings"
89
"text/template"
910

1011
"github.com/Masterminds/sprig/v3"
@@ -26,6 +27,7 @@ type goTemplateData struct {
2627
Functions []phpFunction
2728
Classes []phpClass
2829
Module *phpModule
30+
HasInitFunction bool
2931
}
3032

3133
func (gg *GoFileGenerator) generate() error {
@@ -55,6 +57,16 @@ func (gg *GoFileGenerator) buildContent() (string, error) {
5557
classes := make([]phpClass, len(gg.generator.Classes))
5658
copy(classes, gg.generator.Classes)
5759

60+
// Check if there's already an init() function in the source file
61+
hasInitFunction := false
62+
for _, fn := range internalFunctions {
63+
if strings.HasPrefix(fn, "func init()") {
64+
hasInitFunction = true
65+
fmt.Printf("Warning: An init() function already exists in the source file. Make sure to call frankenphp.RegisterExtension(unsafe.Pointer(&C.ext_module_entry)) in your init function.\n")
66+
break
67+
}
68+
}
69+
5870
templateContent, err := gg.getTemplateContent(goTemplateData{
5971
PackageName: SanitizePackageName(gg.generator.BaseName),
6072
BaseName: gg.generator.BaseName,
@@ -64,6 +76,7 @@ func (gg *GoFileGenerator) buildContent() (string, error) {
6476
Functions: gg.generator.Functions,
6577
Classes: classes,
6678
Module: gg.generator.Module,
79+
HasInitFunction: hasInitFunction,
6780
})
6881

6982
if err != nil {

internal/extgen/templates/extension.go.tpl

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,11 @@ import "runtime/cgo"
1010
import {{.}}
1111
{{- end}}
1212

13+
{{if not .HasInitFunction}}
1314
func init() {
1415
frankenphp.RegisterExtension(unsafe.Pointer(&C.ext_module_entry))
1516
}
17+
{{end}}
1618
{{range .Constants}}
1719
const {{.Name}} = {{.Value}}
1820
{{- end}}

0 commit comments

Comments
 (0)