claviron-php-embed 0.2.0-alpha.18

Managed in-process PHP execution, application hosting, and native extensions for Claviron
use std::convert::Infallible;
use std::sync::Arc;

use claviron_http::{HttpExchange, RouteBody, RouteResponse};
use claviron_php::PhpRuntime;
use http::Request;
use tokio::sync::mpsc::Sender;

use crate::PhpScriptService;
use crate::routing::proxy::upstream_sapi_gateway;

#[derive(Clone)]
pub struct PhpScriptAdapter {
    php: Arc<PhpScriptService>,
    runtime: Arc<PhpRuntime>,
    exchange_tx: Option<Sender<HttpExchange>>,
}

impl PhpScriptAdapter {
    pub fn new(
        php: Arc<PhpScriptService>,
        host_cfg: Arc<PhpRuntime>,
    ) -> Self {
        Self { php, runtime: host_cfg, exchange_tx: None }
    }

    pub fn with_exchange_tx(
        mut self,
        tx: Option<Sender<HttpExchange>>,
    ) -> Self {
        self.exchange_tx = tx;
        self
    }

    pub async fn handle(
        &self,
        req: Request<RouteBody>,
    ) -> Result<RouteResponse, Infallible> {
        Ok(upstream_sapi_gateway(
            Arc::clone(&self.php),
            Arc::clone(&self.runtime),
            req,
            self.exchange_tx.clone(),
        )
        .await)
    }
}