Skip to content

Instantly share code, notes, and snippets.

@lukaskleinschmidt
Created January 23, 2025 16:40
Show Gist options
  • Save lukaskleinschmidt/4b7192df3c6b48f63de56c9ee56fda2c to your computer and use it in GitHub Desktop.
Save lukaskleinschmidt/4b7192df3c6b48f63de56c9ee56fda2c to your computer and use it in GitHub Desktop.
Kirby plugin priority
<?php
namespace App\Foundation;
use Kirby\Cms\App as BaseApp;
class App extends BaseApp
{
/**
* Custom plugin priority
*/
protected static array $pluginPriority = [
//
];
/**
* Loads all plugins from site/plugins
*/
protected function pluginsLoader(): array
{
$loaded = parent::pluginsLoader();
static::$plugins = (new Plugins(
static::$pluginPriority,
static::$plugins,
))->data();
return $loaded;
}
}
<?php
namespace App\Foundation;
use Kirby\Cms\Plugin;
use Kirby\Toolkit\Collection;
class Plugins extends Collection
{
/**
* Constructor
*/
public function __construct(array $priority, array $plugins)
{
$this->data = $this->sortPlugins($priority, $plugins);
}
/**
* Sort the plugins by the given priority
*/
protected function sortPlugins(array $priority, array $plugins): array
{
$prevIndex = 0;
$index = 0;
foreach ($plugins as $name => $plugin) {
$priorityIndex = $this->priorityIndex($priority, $name);
if (! is_null($priorityIndex)) {
if (isset($prevPriorityIndex) && $priorityIndex < $prevPriorityIndex) {
return $this->sortPlugins(
$priority, $this->movePlugin($plugins, $plugin, $prevIndex)
);
}
$prevPriorityIndex = $priorityIndex;
$prevIndex = $index;
}
$index++;
}
return $plugins;
}
/**
* Calculate the priority index of the plugin
*/
protected function priorityIndex($priority, $name): ?int
{
$index = array_search($name, $priority);
if ($index !== false) {
return $index;
}
return null;
}
/**
* Move the plugin to the index while preserving the keys
*/
protected function movePlugin(array $plugins, Plugin $plugin, int $index): array
{
return array_slice($plugins, 0, $index, true)
+ [$plugin->name() => $plugin]
+ array_slice($plugins, $index, null, true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment