Skip to content

Instantly share code, notes, and snippets.

@masakielastic
Last active February 27, 2026 00:48
Show Gist options
  • Select an option

  • Save masakielastic/8e4907ae5dedf1baafe77afa5d9e8a22 to your computer and use it in GitHub Desktop.

Select an option

Save masakielastic/8e4907ae5dedf1baafe77afa5d9e8a22 to your computer and use it in GitHub Desktop.
ext-php-rs で PHP スクリプトを実行する CLI を作成する

ext-php-rs で PHP スクリプトを実行する CLI を作成する

ソースコード

Cargo.toml

[package]
name = "mytool"
version = "0.1.0"
edition = "2021"

[dependencies]
ext-php-rs = { version = "0.15", features = ["embed"] }

src/main.rs

use std::{env, path::PathBuf, process};

use ext_php_rs::embed::{Embed, EmbedError};

fn usage_and_exit(bin: &str) -> ! {
    eprintln!("Usage: {bin} <path/to/script.php>");
    process::exit(2);
}

fn main() {
    let mut args = env::args_os();
    let bin = args
        .next()
        .and_then(|s| s.into_string().ok())
        .unwrap_or_else(|| "mytool".to_string());

    let script_path = match args.next() {
        Some(p) => PathBuf::from(p),
        None => usage_and_exit(&bin),
    };

    if script_path.as_os_str() == "-h" || script_path.as_os_str() == "--help" {
        usage_and_exit(&bin);
    }

    if !script_path.is_file() {
        eprintln!("Error: script not found or not a file: {}", script_path.display());
        process::exit(1);
    }

    // ★ ここで UTF-8 を保証してしまう(EmbedError を作らない)
    let script_str = match script_path.to_str() {
        Some(s) => s.to_owned(),
        None => {
            eprintln!("Error: script path is not valid UTF-8: {}", script_path.display());
            process::exit(1);
        }
    };

    // ★ Embed::run は R: Default なので、R=() にしてエラーは外へ運ぶ
    let mut err: Option<EmbedError> = None;

    Embed::run(|| {
        if let Err(e) = Embed::run_script(&script_str) {
            err = Some(e);
        }
    });

    if let Some(e) = err {
        eprintln!("PHP script failed: {e:?}");
        process::exit(1);
    }
}

実行

cargo build
target/debug/mytool test.php
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment