jdrouet / mrml

Implementation of mjml in rust
MIT License
355 stars 22 forks source link

Ability to provide mjml as input vs a file path #151

Closed zachzurn closed 3 years ago

zachzurn commented 3 years ago

Using mrml-cli from a legacy PHP codebase where the MJML is dynamically generated. In order to use the cli, a temp file has to be written to that has a .mjml extension in order to use the cli.

Sample of the current approach from PHP:

//Create a unique temp file
$tempPath = tempnam(sys_get_temp_dir(), 'mjml-compiler-');
//Hacky, use the same path but with the mjml extension
$tempMjmlPath = $tempPath . '.mjml';

//Write the MJML to the file
file_put_contents($tempMjmlPath, $mjml);

//Run the file through the cli
$arguments = [
    __DIR__ . '/../../../bin/mrml', //Executable path
    $tempMjmlPath, //mjml path
    'render', //The command
];

$process = new Process($arguments);

try {
    //Run and return output
    $process->mustRun();
    $output = $process->getOutput();
    return $output;
} catch (ProcessFailedException $e) {
    //Fallback to the api until mrml can have a non strict mode (A ticket exists for this)
    return self::apiRender($mjml);
} finally {
    unlink($tempPath); //delete the empty file that tempnam creates
    unlink($tempMjmlPath); //to delete the temp MJML file    
}

Possibly if no path is provided, for example mjml-cli render the cli could ask for input instead which would avoid the need to write to and read from a file.

Sample with using cli input method:

//Run the file through the cli
$arguments = [
    __DIR__ . '/../../../bin/mrml', //Executable path
    $tempMjmlPath, //mjml path
    'render', //The command
];

$process = new Process($arguments);
$process->setInput($mjml);

try {
    //Run and return output
    $process->mustRun();
    $output = $process->getOutput();
    return $output;
} catch (ProcessFailedException $e) {
    //Fallback to the api until mrml can have a non strict mode (A ticket exists for this)
    return self::apiRender($mjml);
}
zachzurn commented 3 years ago

Tested (mjml-cli 1.3) and this is working correctly using stdin!