| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCart\App\Services\Libs\Emogrifier; |
| 4 |
|
| 5 |
class Emogrifier |
| 6 |
{ |
| 7 |
private $html = ''; |
| 8 |
|
| 9 |
public function __construct($html) |
| 10 |
{ |
| 11 |
$this->html = (string) $html; |
| 12 |
} |
| 13 |
|
| 14 |
public function emogrify() |
| 15 |
{ |
| 16 |
if (!class_exists('\FluentEmogrifier\Vendor\TijsVerkoyen\CssToInlineStyles\CssToInlineStyles')) { |
| 17 |
require_once __DIR__ . '/scoped-vendor/autoload.php'; |
| 18 |
} |
| 19 |
|
| 20 |
return $this->handleTijsVerkoyen(); |
| 21 |
} |
| 22 |
|
| 23 |
private function handleTijsVerkoyen() |
| 24 |
{ |
| 25 |
$css = ''; |
| 26 |
$html = $this->html; |
| 27 |
|
| 28 |
if (preg_match_all('/<style[^>]*>(.*?)<\/style>/si', $html, $matches)) { |
| 29 |
$css = implode("\n", $matches[1]); |
| 30 |
$html = preg_replace('/<style[^>]*>.*?<\/style>/si', '', $html); |
| 31 |
} |
| 32 |
|
| 33 |
// Preserve @media queries — TijsVerkoyen strips them during CSS processing |
| 34 |
// but email clients like Apple Mail and Gmail support them for responsive layouts. |
| 35 |
// Regex handles both spaced (@media screen) and minified (@media(max-width:600px)) forms. |
| 36 |
$mediaBlocks = ''; |
| 37 |
if (preg_match_all('/@media\s*[^{]*\{(?:[^{}]*\{[^{}]*\})*[^{}]*\}/s', $css, $mediaMatches)) { |
| 38 |
$mediaBlocks = implode("\n", $mediaMatches[0]); |
| 39 |
} |
| 40 |
|
| 41 |
$inliner = new \FluentEmogrifier\Vendor\TijsVerkoyen\CssToInlineStyles\CssToInlineStyles(); |
| 42 |
$result = $inliner->convert($html, $css); |
| 43 |
|
| 44 |
// Re-inject @media blocks for responsive email support |
| 45 |
if ($mediaBlocks) { |
| 46 |
$styleTag = '<style type="text/css">' . $mediaBlocks . '</style>'; |
| 47 |
|
| 48 |
if (stripos($result, '</head>') !== false) { |
| 49 |
$result = str_ireplace('</head>', $styleTag . '</head>', $result); |
| 50 |
} elseif (stripos($result, '<body') !== false) { |
| 51 |
$result = preg_replace('/<body/i', $styleTag . '<body', $result, 1); |
| 52 |
} else { |
| 53 |
$result = $styleTag . $result; |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
return $result; |
| 58 |
} |
| 59 |
|
| 60 |
} |
| 61 |
|