Skip to content

Commit

Permalink
feat: add CLI support
Browse files Browse the repository at this point in the history
  • Loading branch information
dunglas committed May 23, 2022
1 parent 6da01cc commit 767f59c
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 0 deletions.
16 changes: 16 additions & 0 deletions frankenphp.c
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#include <php_variables.h>
#include <php_output.h>
#include <Zend/zend_alloc.h>
#include <sapi/embed/php_embed.h>
#include "_cgo_export.h"

// Helper functions copied from the PHP source code
Expand Down Expand Up @@ -546,3 +547,18 @@ int frankenphp_execute_script(const char* file_name)

return status;
}

int frankenphp_execute_script_cli(char *script, int argc, char **argv) {
PHP_EMBED_START_BLOCK(argc, argv)

zend_file_handle file_handle;
zend_stream_init_filename(&file_handle, script);

if (php_execute_script(&file_handle) == FAILURE) {
return FAILURE;
}

PHP_EMBED_END_BLOCK()

return SUCCESS;
}
19 changes: 19 additions & 0 deletions frankenphp.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,25 @@ func updateServerContext(request *http.Request) error {
return nil
}

func ExecuteScriptCLI(script string, args []string) error {
cScript := C.CString(script)
defer C.free(unsafe.Pointer(cScript))

argc := C.int(len(args))
argv := make([]*C.char, argc)
for i, arg := range args {
argv[i] = C.CString(arg)
}

runtime.LockOSThread()

if C.frankenphp_execute_script_cli(cScript, argc, (**C.char)(unsafe.Pointer(&argv[0]))) == -1 {
return fmt.Errorf("error exuction script %s", script)
}

return nil
}

func ExecuteScript(responseWriter http.ResponseWriter, request *http.Request) error {
if atomic.LoadInt32(&started) < 1 {
panic("FrankenPHP isn't started, call frankenphp.Startup()")
Expand Down
2 changes: 2 additions & 0 deletions frankenphp.h
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,6 @@ int frankenphp_request_startup();
int frankenphp_execute_script(const char *file_name);
uintptr_t frankenphp_request_shutdown();

int frankenphp_execute_script_cli(char *script, int argc, char **argv);

#endif
6 changes: 6 additions & 0 deletions frankenphp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,12 @@ func testPhpInfo(t *testing.T, scriptName string) {
}
}

func TestExecuteScriptCLI(t *testing.T) {
cwd, _ := os.Getwd()

assert.Nil(t, frankenphp.ExecuteScriptCLI(cwd+"/testdata/command.php", []string{"foo", "bar"}))
}

func ExampleExecuteScript() {
frankenphp.Startup()
defer frankenphp.Shutdown()
Expand Down
3 changes: 3 additions & 0 deletions testdata/command.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<?php

echo "From the CLI\n";

0 comments on commit 767f59c

Please sign in to comment.