1
0
mirror of https://github.com/flarum/core.git synced 2025-08-18 06:11:23 +02:00

feat: add Less custom function extender, is-extension-enabled function (#3190)

Co-authored-by: luceos <luceos@users.noreply.github.com>
Co-authored-by: Sami Mazouz <sychocouldy@gmail.com>
This commit is contained in:
David Wheatley
2021-12-14 19:25:39 +00:00
committed by GitHub
parent 25dc26bac6
commit 11fd012f70
6 changed files with 129 additions and 2 deletions

View File

@@ -12,11 +12,13 @@ namespace Flarum\Extend;
use Flarum\Extension\Extension;
use Flarum\Frontend\Assets;
use Illuminate\Contracts\Container\Container;
use RuntimeException;
class Theme implements ExtenderInterface
{
private $lessImportOverrides = [];
private $fileSourceOverrides = [];
private $customFunctions = [];
/**
* This can be used to override LESS files that are imported within the code.
@@ -52,8 +54,58 @@ class Theme implements ExtenderInterface
return $this;
}
/**
* This method allows you to add custom Less functions.
*
* All custom Less functions may only return numbers, strings or booleans.
*
* **Example usage:**
* ```php
* (new Extend\Theme)
* ->addCustomLessFunction('is-flarum', function (mixed $text) {
* return strtolower($text) === 'flarum'
* }),
* ```
*
* @see https://leafo.net/lessphp/docs/#custom_functions
*
* @param string $functionName Name of the function identifier.
* @param callable $callable The PHP function to run when the Less function is called.
* @return self
*/
public function addCustomLessFunction(string $functionName, callable $callable): self
{
$this->customFunctions[$functionName] = function (...$args) use ($callable, $functionName) {
$argVals = array_map(function ($arg) {
return $arg->value;
}, $args);
$return = $callable(...$argVals);
if (is_bool($return)) {
return new \Less_Tree_Quoted('', $return ? 'true' : 'false');
}
if (is_string($return)) {
return new \Less_Tree_Quoted('', $return);
}
if (is_numeric($return)) {
return new \Less_Tree_Dimension($return);
}
throw new RuntimeException('Custom Less function `'.$functionName.'` must only return a string, number or boolean.');
};
return $this;
}
public function extend(Container $container, Extension $extension = null)
{
$container->extend('flarum.frontend.custom_less_functions', function (array $customFunctions) {
return array_merge($customFunctions, $this->customFunctions);
});
$container->extend('flarum.assets.factory', function (callable $factory) {
return function (...$args) use ($factory) {
/** @var Assets $assets */