I'm trying to switch my plugins to oop style. For better testability I want to stay away from WordPress as much as possible. Without knowing of this Composer package, I started to implement my own asset management abstraction (mostly inspired by https://github.com/schlessera/as-speaking). Now I'm trying to use this package.
<?php
declare(strict_types=1);
namespace Plugin\Metabox;
use RegisterableInterface;
use Renderer\RendererInterface;
use Inpsyde\Assets\{Asset, AssetManager, Handler\ScriptHandler, Script};
use Throwable;
final class Github implements RegisterableInterface
{
private const ID = 'gh-metabox';
private const JS_HANDLE = 'gh-metabox';
/** @var RendererInterface */
private $renderer;
/** @var AssetManager */
private $assetManager;
public function __construct(
RendererInterface $renderer,
AssetManager $assetManager
) {
$this->renderer = $renderer;
$this->assetManager = $assetManager;
}
public function register(): void
{
$pluginName = plugin_basename(dirname(__DIR__, 2));
$url = plugins_url() . '/' . $pluginName . '/assets/js/gh.js';
$script = new Script(self::JS_HANDLE, $url, Asset::BACKEND, ['enqueue' => false]);
$script->withLocalize('foo', 'bar');
$this->assetManager->register($script);
add_action('add_meta_boxes', function () {
add_meta_box(
self::ID,
'Github',
[$this, 'process']
);
});
}
public function process(): void
{
/** @var Script $script */
$script = $this->assetManager->asset(self::JS_HANDLE, Script::class);
if ($script) {
$script->canEnqueue(true);
$scriptHandler = $this->assetManager->handlers()[ScriptHandler::class];
$scriptHandler->enqueue($script);
}
try {
echo $this->renderer->render('gh-metabox');
} catch (Throwable $e) {
echo sprintf('<pre>%s</pre>', $e->getMessage());
}
}
}