Skip to content

Commit

Permalink
Merge pull request #26 from spatie/feature/generate-using-cli
Browse files Browse the repository at this point in the history
Generate using a file with the cli when generating locally
  • Loading branch information
freekmurze authored Jan 17, 2025
2 parents e31e7be + 93d211e commit 70329ca
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 73 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/run-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ jobs:
strategy:
fail-fast: true
matrix:
os: [ubuntu-latest, windows-latest]
php: [8.3, 8.2, 8.1]
stability: [prefer-lowest, prefer-stable]
os: [ubuntu-latest]
php: [8.4, 8.3, 8.2, 8.1]
stability: [prefer-stable]

name: P${{ matrix.php }} - ${{ matrix.stability }} - ${{ matrix.os }}

Expand Down
28 changes: 0 additions & 28 deletions bin/mjml.mjs

This file was deleted.

1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
],
"require": {
"php": "^8.1",
"spatie/temporary-directory": "^2.2",
"symfony/process": "^6.3.2|^7.0"
},
"require-dev": {
Expand Down
117 changes: 76 additions & 41 deletions src/Mjml.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
use Spatie\Mjml\Exceptions\CouldNotConvertMjml;
use Spatie\Mjml\Exceptions\SidecarPackageUnavailable;
use Spatie\MjmlSidecar\MjmlFunction;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Spatie\TemporaryDirectory\TemporaryDirectory;
use Symfony\Component\Process\ExecutableFinder;
use Symfony\Component\Process\Process;

Expand All @@ -23,8 +23,6 @@ class Mjml

protected string $filePath = '.';

protected string $workingDirectory;

protected bool $sidecar = false;

public static function new(): self
Expand All @@ -35,8 +33,6 @@ public static function new(): self
protected function __construct()
{
$this->validationLevel = ValidationLevel::Soft;

$this->workingDirectory = realpath(dirname(__DIR__).'/bin');
}

public function keepComments(bool $keepComments = true): self
Expand Down Expand Up @@ -93,13 +89,6 @@ public function filePath(string $filePath): self
return $this;
}

public function workingDirectory(string $workingDirectory): self
{
$this->workingDirectory = $workingDirectory;

return $this;
}

public function canConvert(string $mjml): bool
{
try {
Expand Down Expand Up @@ -134,19 +123,11 @@ public function convert(string $mjml, array $options = []): MjmlResult
$this->configOptions($options),
];

$resultString = $this->sidecar
? $this->getSideCarResult($arguments)
: $this->getLocalResult($arguments);

$resultString = $this->checkForDeprecationWarning($resultString);

$resultProperties = json_decode($resultString, true);

if (array_key_exists('mjmlError', $resultProperties)) {
throw CouldNotConvertMjml::make($resultProperties['mjmlError']);
if ($this->sidecar) {
return $this->getSideCarResult($arguments);
}

return new MjmlResult($resultProperties);
return $this->getLocalResult($arguments);
}

protected function checkForDeprecationWarning(string $result): string
Expand All @@ -160,24 +141,36 @@ protected function checkForDeprecationWarning(string $result): string
return $result;
}

protected function getCommand(array $arguments): array
protected function getCommand(string $templatePath, string $outputPath, $arguments): array
{
$home = getenv('HOME');

$extraDirectories = [
'/usr/local/bin',
'/opt/homebrew/bin',
$home.'/n/bin', // support https://github.com/tj/n
__DIR__.'/../node_modules/mjml/bin',
];

$nodePathFromEnv = getenv('MJML_NODE_PATH');
$mjmlPathFromEnv = getenv('MJML_PATH');

if ($nodePathFromEnv) {
array_unshift($extraDirectories, $nodePathFromEnv);
if ($mjmlPathFromEnv) {
array_unshift($extraDirectories, $mjmlPathFromEnv);
}

return [
(new ExecutableFinder)->find('node', 'node', $extraDirectories),
'mjml.mjs',
base64_encode(json_encode(array_values($arguments))),
$command = [
(new ExecutableFinder)->find('mjml', 'mjml', $extraDirectories),
$templatePath,
'-o',
$outputPath,
];

foreach ($arguments as $configKey => $configValue) {
$command[] = "-c.{$configKey}";
$command[] = $configValue;
}

return $command;
}

protected function configOptions(array $overrides): array
Expand All @@ -194,33 +187,75 @@ protected function configOptions(array $overrides): array
return array_merge($defaults, $overrides);
}

protected function getSideCarResult(array $arguments): string
protected function getSideCarResult(array $arguments): MjmlResult
{
if (! class_exists(MjmlFunction::class)) {
throw SidecarPackageUnavailable::make();
}

return MjmlFunction::execute([
$result = MjmlFunction::execute([
'mjml' => $arguments[0],
'options' => $arguments[1],
])->body();

$result = $this->checkForDeprecationWarning($result);

$resultProperties = json_decode($result, true);

if (array_key_exists('mjmlError', $resultProperties)) {
throw CouldNotConvertMjml::make($resultProperties['mjmlError']);
}

return new MjmlResult($resultProperties);
}

protected function getLocalResult(array $arguments): string
protected function getLocalResult(array $arguments): MjmlResult
{
$process = new Process(
$this->getCommand($arguments),
$this->workingDirectory,
);
$tempDir = TemporaryDirectory::make();
$filename = date('U');

$templatePath = $tempDir->path("{$filename}.mjml");
file_put_contents($templatePath, $arguments[0]);

$outputPath = $tempDir->path("{$filename}.html");

$command = $this->getCommand($templatePath, $outputPath, $arguments[1]);

$process = new Process($command);
$process->run();

if (! $process->isSuccessful()) {
throw new ProcessFailedException($process);
$output = explode("\n", $process->getErrorOutput());
$errors = array_filter($output, fn (string $output) => str_contains($output, 'Error'));

$tempDir->delete();

throw CouldNotConvertMjml::make($errors[0] ?? $process->getErrorOutput());
}

$errors = [];

if ($process->getErrorOutput()) {
$errors = array_filter(explode("\n", $process->getErrorOutput()));
$errors = array_map(function (string $error) {
preg_match('/Line (\d+) of (.+) \((.+)\) — (.+)/u', $error, $matches);
[, $line, , $tagName, $message] = $matches;

return [
'line' => $line,
'message' => $message,
'tagName' => $tagName,
];
}, $errors);
}

$items = explode("\n", $process->getOutput());
$html = file_get_contents($outputPath);

$tempDir->delete();

return base64_decode(end($items));
return new MjmlResult([
'html' => $html,
'errors' => $errors,
]);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
display: block;
margin: 13px 0;
}

</style>
<!--[if mso]>
<noscript>
Expand All @@ -60,6 +61,7 @@
<link href="https://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700" rel="stylesheet" type="text/css">
<style type="text/css">
@import url(https://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700);

</style>
<!--<![endif]-->
<style type="text/css">
Expand All @@ -69,12 +71,14 @@
max-width: 100%;
}
}

</style>
<style media="screen and (min-width:480px)">
.moz-text-html .mj-column-per-100 {
width: 100% !important;
max-width: 100%;
}

</style>
</head>

Expand Down Expand Up @@ -108,4 +112,4 @@
</div>
</body>

</html>
</html>

0 comments on commit 70329ca

Please sign in to comment.