xiaowang/kirby/src/Panel/Plugins.php

110 lines
2.5 KiB
PHP
Raw Normal View History

2021-10-29 18:05:46 +02:00
<?php
2021-11-18 17:44:47 +01:00
namespace Kirby\Panel;
2021-10-29 18:05:46 +02:00
2021-11-18 17:44:47 +01:00
use Kirby\Cms\App;
use Kirby\Filesystem\F;
2021-10-29 18:05:46 +02:00
use Kirby\Toolkit\Str;
/**
2021-11-18 17:44:47 +01:00
* The Plugins class takes care of collecting
2021-10-29 18:05:46 +02:00
* js and css plugin files for the panel and caches
* them in the media folder
*
2021-11-18 17:44:47 +01:00
* @package Kirby Panel
2021-10-29 18:05:46 +02:00
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier GmbH
* @license https://getkirby.com/license
*/
2021-11-18 17:44:47 +01:00
class Plugins
2021-10-29 18:05:46 +02:00
{
/**
* Cache of all collected plugin files
*
* @var array
*/
public $files;
/**
* Collects and returns the plugin files for all plugins
*
* @return array
*/
public function files(): array
{
if ($this->files !== null) {
return $this->files;
}
$this->files = [];
foreach (App::instance()->plugins() as $plugin) {
$this->files[] = $plugin->root() . '/index.css';
$this->files[] = $plugin->root() . '/index.js';
}
return $this->files;
}
/**
* Returns the last modification
* of the collected plugin files
*
* @return int
*/
public function modified(): int
{
$files = $this->files();
$modified = [0];
foreach ($files as $file) {
$modified[] = F::modified($file);
}
return max($modified);
}
/**
* Read the files from all plugins and concatenate them
*
* @param string $type
* @return string
*/
public function read(string $type): string
{
$dist = [];
foreach ($this->files() as $file) {
if (F::extension($file) === $type) {
if ($content = F::read($file)) {
if ($type === 'js') {
$content = trim($content);
// make sure that each plugin is ended correctly
if (Str::endsWith($content, ';') === false) {
$content .= ';';
}
}
$dist[] = $content;
}
}
}
return implode(PHP_EOL . PHP_EOL, $dist);
}
/**
* Absolute url to the cache file
* This is used by the panel to link the plugins
*
* @param string $type
* @return string
*/
public function url(string $type): string
{
return App::instance()->url('media') . '/plugins/index.' . $type . '?' . $this->modified();
}
}