├── .github ├── FUNDING.yml └── workflows │ └── run-tests.yml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── composer.json └── src ├── BladeOnDemandRenderer.php ├── BladeOnDemandServiceProvider.php └── Facades └── BladeOnDemand.php /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [pascalbaljet] 2 | -------------------------------------------------------------------------------- /.github/workflows/run-tests.yml: -------------------------------------------------------------------------------- 1 | name: run-tests 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | test: 7 | runs-on: ubuntu-latest 8 | strategy: 9 | fail-fast: true 10 | matrix: 11 | php: [8.4, 8.3, 8.2] 12 | laravel: [12.0, 11.43, 10.48] 13 | dependency-version: [prefer-lowest, prefer-stable] 14 | include: 15 | - laravel: 12.0 16 | testbench: 10.0 17 | - laravel: 11.43 18 | testbench: 9.11 19 | - laravel: 10.48 20 | testbench: 8.33 21 | 22 | name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} 23 | 24 | steps: 25 | - name: Checkout code 26 | uses: actions/checkout@v2 27 | 28 | - name: Cache dependencies 29 | uses: actions/cache@v2 30 | with: 31 | path: ~/.composer/cache/files 32 | key: dependencies-laravel-${{ matrix.laravel }}-php-${{ matrix.php }}-composer-${{ hashFiles('composer.json') }} 33 | 34 | - name: Setup PHP 35 | uses: shivammathur/setup-php@v2 36 | with: 37 | php-version: ${{ matrix.php }} 38 | extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick, mysql, mysqli, pdo_mysql 39 | coverage: none 40 | 41 | - name: Install dependencies 42 | run: | 43 | composer require "laravel/framework:^${{ matrix.laravel }}" "orchestra/testbench:^${{ matrix.testbench }}" --no-interaction --no-update 44 | composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction --no-suggest 45 | 46 | - name: Execute tests 47 | run: vendor/bin/phpunit 48 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `laravel-blade-on-demand` will be documented in this file 4 | 5 | ## 1.5.0 - 2022-02-04 6 | 7 | - Support for Laravel 9 8 | 9 | ## 1.4.0 - 2021-12-19 10 | 11 | - Support for PHP 8.1 12 | - Dropped support for PHP 7.3 13 | - Dropped support for Laravel 6 and 7 14 | 15 | ## 1.3.0 - 2020-10-31 16 | 17 | - Support for PHP 8.0 18 | - Dropped support for PHP 7.2 19 | 20 | ## 1.2.0 - 2020-09-04 21 | 22 | - Support for Laravel 8.0 23 | 24 | ## 1.1.1 - 2020-03-16 25 | 26 | - Minor refactor 27 | 28 | ## 1.1.0 - 2020-03-16 29 | 30 | - Support for Mailable themes 31 | - Support for handling missing variables 32 | - Better documentation 33 | 34 | ## 1.0.0 - 2020-03-10 35 | 36 | - Initial release 37 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Pascal Baljet 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Laravel Blade On Demand 2 | 3 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/protonemedia/laravel-blade-on-demand.svg?style=flat-square)](https://packagist.org/packages/protonemedia/laravel-blade-on-demand) 4 | ![run-tests](https://github.com/protonemedia/laravel-blade-on-demand/workflows/run-tests/badge.svg) 5 | [![Quality Score](https://img.shields.io/scrutinizer/g/protonemedia/laravel-blade-on-demand.svg?style=flat-square)](https://scrutinizer-ci.com/g/protonemedia/laravel-blade-on-demand) 6 | [![Total Downloads](https://img.shields.io/packagist/dt/protonemedia/laravel-blade-on-demand.svg?style=flat-square)](https://packagist.org/packages/protonemedia/laravel-blade-on-demand) 7 | 8 | Laravel package to compile Blade templates in memory. Requires PHP 8.2 or higher, compatible with Laravel 10+. 9 | 10 | ## Sponsor Us 11 | 12 | [](https://inertiaui.com/inertia-table?utm_source=github&utm_campaign=laravel-blade-on-demand) 13 | 14 | ❤️ We proudly support the community by developing Laravel packages and giving them away for free. If this package saves you time or if you're relying on it professionally, please consider [sponsoring the maintenance and development](https://github.com/sponsors/pascalbaljet) and check out our latest premium package: [Inertia Table](https://inertiaui.com/inertia-table?utm_source=github&utm_campaign=laravel-blade-on-demand). Keeping track of issues and pull requests takes time, but we're happy to help! 15 | 16 | ## Installation 17 | 18 | You can install the package via composer: 19 | 20 | ```bash 21 | composer require protonemedia/laravel-blade-on-demand 22 | ``` 23 | 24 | ## Usage 25 | 26 | ### Render Blade template 27 | 28 | You can render any valid [Blade Template](https://laravel.com/docs/7.x/blade) by calling the `render` method on the `BladeOnDemand` facade. The method only takes two parameters, the template content and the data you want to pass to the template. 29 | 30 | ``` php 31 | $output = BladeOnDemand::render('Hello {{ $name }}', ['name' => 'Protone Media']); 32 | 33 | echo $output; 34 | 35 | // "Hello Protone Media" 36 | ``` 37 | 38 | This is a just an example but you can use statements, components and other Blade features as well. 39 | 40 | ### Handle missing variables 41 | 42 | This feature prevents your render from failing whenever a variable is missing in your data array. By default it will fill the missing variable with the name of the variable itself. In this case `$name` is missing so the data array becomes `['name' => 'name']`; 43 | 44 | ``` php 45 | $output = BladeOnDemand::fillMissingVariables()->render('Hello {{ $name }}', []); 46 | 47 | echo $output; 48 | 49 | // "Hello name" 50 | ``` 51 | 52 | You could also use this feature to preview a template without any data. Note that this might give unexpected results when using statements. You can also pass a `callable` to the `fillMissingVariables` method to customize the handling of missing variables: 53 | 54 | ``` php 55 | $output = BladeOnDemand::fillMissingVariables( 56 | fn ($variable) => "_MISSING_{$variable}_MISSING_" 57 | )->render('Hello {{ $name }}'); 58 | 59 | echo $output; 60 | 61 | // "Hello _MISSING_name_MISSING_" 62 | ``` 63 | 64 | ### Render Markdown Mail to HTML 65 | 66 | This feature can be used to render a mail as if you're using a [Markdown mailable](https://laravel.com/docs/7.x/mail#writing-markdown-messages). 67 | 68 | ``` php 69 | $contents = implode(PHP_EOL, [ 70 | '@component("mail::message")', 71 | '# Hello {{ $name }}', 72 | '@endcomponent', 73 | ]); 74 | 75 | $output = BladeOnDemand::renderMarkdownMailToHtml($contents, ['name' => 'Protone Media']); 76 | 77 | echo $output; 78 | 79 | // 80 | // 81 | // 82 | // ... 83 | // 84 | // 85 | // 88 | 89 | // 90 | // ... 91 | //

Hello Protone Media

92 | // ... 93 | //
94 | // 95 | // 96 | ``` 97 | 98 | You can optionally specify a theme, just like calling the `theme` method [on a Mailable](https://laravel.com/docs/7.x/notifications#customizing-the-components). 99 | 100 | ```php 101 | BladeOnDemand::theme('invoice')->renderMarkdownMailToHtml($contents, $data); 102 | ``` 103 | 104 | ### Render Markdown Mail to text 105 | 106 | Similair feature as the above `renderMarkdownMailToHtml` method except it uses components from the `text` directory. You can read more about this feature in the [Laravel documentation](https://laravel.com/docs/7.x/mail#customizing-the-components). 107 | 108 | ```php 109 | $contents = implode(PHP_EOL, [ 110 | '@component("mail::message")', 111 | '# Hello {{ $name }}', 112 | '@endcomponent', 113 | ]); 114 | 115 | $output = BladeOnDemand::renderMarkdownMailToText($contents, ['name' => 'Protone Media']); 116 | 117 | echo $output; 118 | 119 | // [AppName](http://localhost) 120 | // 121 | // # Hello Protone Media 122 | // 123 | // © 2020 AppName. All rights reserved. 124 | ``` 125 | 126 | ### Parse Maildown Mail 127 | 128 | The `parseMarkdownMail` method is the same as the `renderMarkdownMailToText` method but it also parses the Markdown. 129 | 130 | ```php 131 | $contents = implode(PHP_EOL, [ 132 | '@component("mail::message")', 133 | '# Hello {{ $name }}', 134 | '@endcomponent', 135 | ]); 136 | 137 | $output = BladeOnDemand::parseMarkdownMail($contents, ['name' => 'Protone Media']); 138 | 139 | echo $output; 140 | 141 | //

AppName

142 | //

Hello Protone Media

143 | //

© 2020 AppName. All rights reserved.

144 | ``` 145 | 146 | ### Testing 147 | 148 | ``` bash 149 | composer test 150 | ``` 151 | 152 | ### Changelog 153 | 154 | Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. 155 | 156 | ## Contributing 157 | 158 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 159 | 160 | ## Other Laravel packages 161 | 162 | * [`Inertia Table`](https://inertiaui.com/inertia-table?utm_source=github&utm_campaign=laravel-blade-on-demand): The Ultimate Table for Inertia.js with built-in Query Builder. 163 | * [`Laravel Cross Eloquent Search`](https://github.com/protonemedia/laravel-cross-eloquent-search): Laravel package to search through multiple Eloquent models. 164 | * [`Laravel Eloquent Scope as Select`](https://github.com/protonemedia/laravel-eloquent-scope-as-select): Stop duplicating your Eloquent query scopes and constraints in PHP. This package lets you re-use your query scopes and constraints by adding them as a subquery. 165 | * [`Laravel FFMpeg`](https://github.com/protonemedia/laravel-ffmpeg): This package provides an integration with FFmpeg for Laravel. The storage of the files is handled by Laravel's Filesystem. 166 | * [`Laravel MinIO Testing Tools`](https://github.com/protonemedia/laravel-minio-testing-tools): Run your tests against a MinIO S3 server. 167 | * [`Laravel Mixins`](https://github.com/protonemedia/laravel-mixins): A collection of Laravel goodies. 168 | * [`Laravel Paddle`](https://github.com/protonemedia/laravel-paddle): Paddle.com API integration for Laravel with support for webhooks/events. 169 | * [`Laravel Task Runner`](https://github.com/protonemedia/laravel-task-runner): Write Shell scripts like Blade Components and run them locally or on a remote server. 170 | * [`Laravel Verify New Email`](https://github.com/protonemedia/laravel-verify-new-email): This package adds support for verifying new email addresses: when a user updates its email address, it won't replace the old one until the new one is verified. 171 | * [`Laravel XSS Protection`](https://github.com/protonemedia/laravel-xss-protection): Laravel Middleware to protect your app against Cross-site scripting (XSS). It sanitizes request input, and it can sanatize Blade echo statements. 172 | 173 | ### Security 174 | 175 | If you discover any security related issues, please email pascal@protone.media instead of using the issue tracker. 176 | 177 | ## Credits 178 | 179 | - [Pascal Baljet](https://github.com/protonemedia) 180 | - [All Contributors](../../contributors) 181 | 182 | ## License 183 | 184 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 185 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "protonemedia/laravel-blade-on-demand", 3 | "description": "Compile Blade templates in memory", 4 | "keywords": [ 5 | "protonemedia", 6 | "laravel-blade-on-demand" 7 | ], 8 | "homepage": "https://github.com/protonemedia/laravel-blade-on-demand", 9 | "license": "MIT", 10 | "type": "library", 11 | "authors": [ 12 | { 13 | "name": "Pascal Baljet", 14 | "email": "pascal@protone.media", 15 | "role": "Developer" 16 | } 17 | ], 18 | "require": { 19 | "php": "^8.4 || ^8.3 || ^8.2", 20 | "illuminate/mail": "^10.48|^11.43|^12.0", 21 | "illuminate/view": "^10.48|^11.43|^12.0" 22 | }, 23 | "require-dev": { 24 | "orchestra/testbench": "^8.33|^9.11|^10.0", 25 | "phpunit/phpunit": "^10.4|^11.5.3" 26 | }, 27 | "autoload": { 28 | "psr-4": { 29 | "ProtoneMedia\\BladeOnDemand\\": "src" 30 | } 31 | }, 32 | "autoload-dev": { 33 | "psr-4": { 34 | "ProtoneMedia\\BladeOnDemand\\Tests\\": "tests" 35 | } 36 | }, 37 | "scripts": { 38 | "test": "vendor/bin/phpunit", 39 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage" 40 | }, 41 | "config": { 42 | "sort-packages": true 43 | }, 44 | "minimum-stability": "dev", 45 | "prefer-stable": true, 46 | "extra": { 47 | "laravel": { 48 | "providers": [ 49 | "ProtoneMedia\\BladeOnDemand\\BladeOnDemandServiceProvider" 50 | ], 51 | "aliases": { 52 | "BladeOnDemand": "ProtoneMedia\\BladeOnDemand\\Facades\\BladeOnDemand" 53 | } 54 | } 55 | } 56 | } -------------------------------------------------------------------------------- /src/BladeOnDemandRenderer.php: -------------------------------------------------------------------------------- 1 | viewFactory = $viewFactory; 44 | $this->markdown = $markdown; 45 | $this->cssInliner = $cssInliner; 46 | 47 | $this->theme = config('mail.markdown.theme', 'default'); 48 | } 49 | 50 | /** 51 | * Fills the missing variables in the template 52 | * 53 | * @param callable $callback 54 | * @return $this 55 | */ 56 | public function fillMissingVariables(callable $callback = null) 57 | { 58 | $this->fillMissingVariables = $callback ?: true; 59 | 60 | return $this; 61 | } 62 | 63 | /** 64 | * Set the default theme to be used. 65 | * 66 | * @param string $theme 67 | * @return $this 68 | */ 69 | public function theme($theme) 70 | { 71 | $this->theme = $theme; 72 | 73 | return $this; 74 | } 75 | 76 | /** 77 | * Renders the content with the given data. 78 | * 79 | * @param string $contents 80 | * @param array $data 81 | * @return string 82 | */ 83 | public function render(string $contents, array $data = []): string 84 | { 85 | if ($this->fillMissingVariables) { 86 | $data = $this->addMissingVariables($contents, $data); 87 | } 88 | 89 | file_put_contents( 90 | $path = tempnam(sys_get_temp_dir(), 'blade-on-demand') . '.blade.php', 91 | $contents 92 | ); 93 | 94 | $this->viewFactory->flushFinderCache(); 95 | 96 | return tap($this->viewFactory->file($path, $data)->render(), function () use ($path) { 97 | unlink($path); 98 | 99 | $this->fillMissingVariables = false; 100 | $this->theme = config('mail.markdown.theme', 'default'); 101 | }); 102 | } 103 | 104 | /** 105 | * Finds all missing variables. 106 | * Source: https://stackoverflow.com/a/19563063 107 | * 108 | * @param string $contents 109 | * @param array $data 110 | * @return array 111 | */ 112 | public function getMissingVariables(string $contents, array $data = []): array 113 | { 114 | $pattern = '/\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)/'; 115 | 116 | preg_match_all($pattern, $contents, $matches); 117 | 118 | $variables = $matches[1] ?? []; 119 | 120 | return array_filter($variables, function ($variable) use ($data) { 121 | return !array_key_exists($variable, $data); 122 | }); 123 | } 124 | 125 | /** 126 | * Makes sure each variable is present in the data array. 127 | * 128 | * @param string $contents 129 | * @param array $data 130 | * @return array 131 | */ 132 | private function addMissingVariables(string $contents, array $data = []): array 133 | { 134 | foreach (static::getMissingVariables($contents, $data) as $variable) { 135 | $data[$variable] = is_callable($this->fillMissingVariables) 136 | ? call_user_func_array($this->fillMissingVariables, [$variable]) 137 | : $variable; 138 | } 139 | 140 | return $data; 141 | } 142 | 143 | /** 144 | * Renders the markdown content to a HTML mail. 145 | * 146 | * @param string $contents 147 | * @param array $data 148 | * @return string 149 | */ 150 | public function renderMarkdownMailToHtml(string $contents, array $data = []): string 151 | { 152 | $this->viewFactory->replaceNamespace('mail', $this->markdown->htmlComponentPaths()); 153 | 154 | $theme = Str::contains($this->theme, '::') 155 | ? $this->theme 156 | : 'mail::themes.' . $this->theme; 157 | 158 | $rendered = $this->render($contents, $data); 159 | 160 | return $this->cssInliner->convert( 161 | $rendered, 162 | $this->viewFactory->make($theme)->render() 163 | ); 164 | } 165 | 166 | /** 167 | * Renders the markdown content to a Text mail. 168 | * 169 | * @param string $contents 170 | * @param array $data 171 | * @return string 172 | */ 173 | public function renderMarkdownMailToText(string $contents, array $data = []): string 174 | { 175 | $this->viewFactory->replaceNamespace('mail', $this->markdown->textComponentPaths()); 176 | 177 | $rendered = $this->render($contents, $data); 178 | 179 | return html_entity_decode(preg_replace("/[\r\n]{2,}/", "\n\n", $rendered), ENT_QUOTES, 'UTF-8'); 180 | } 181 | 182 | /** 183 | * Parses the markdown content. 184 | * 185 | * @param string $contents 186 | * @param array $data 187 | * @return string 188 | */ 189 | public function parseMarkdownMail(string $contents, array $data = []): string 190 | { 191 | return $this->markdown->parse($this->renderMarkdownMailToText($contents, $data)); 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /src/BladeOnDemandServiceProvider.php: -------------------------------------------------------------------------------- 1 | app->singleton('laravel-blade-on-demand', function () { 18 | return new BladeOnDemandRenderer( 19 | app('view'), 20 | app(Markdown::class), 21 | app(CssToInlineStyles::class) 22 | ); 23 | }); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Facades/BladeOnDemand.php: -------------------------------------------------------------------------------- 1 |