<?php
namespace App\Blocks;
use Symfony\Component\Yaml\Yaml;
use Twig\Environment;
class BlockRuntimeDescription
{
private const TEMPLATE_FILE_NAME = 'block.html.twig';
public string $path;
public string $name;
public string $version;
public string $title;
public string $description;
public string $category;
public array $keywords = [];
public bool $overriden = false;
public string $iconPath;
public string $icon;
public ?string $overridenClass = null;
public function __construct(string $basePath, string $blockName)
{
$yaml = Yaml::parseFile($basePath . DIRECTORY_SEPARATOR . "$blockName" . DIRECTORY_SEPARATOR . lcfirst('block.yml'));
if (!isset($yaml['version'], $yaml['title'], $yaml['description'], $yaml['category'])) {
throw new \InvalidArgumentException("Block $blockName is missing required fields in block.yml file.");
}
$this->path = $basePath . DIRECTORY_SEPARATOR . $blockName;
$this->name = $blockName;
$this->version = $yaml['version'];
$this->title = $yaml['title'];
$this->description = $yaml['description'];
$this->category = $yaml['category'];
$this->keywords = $yaml['keywords'] ?? [];
$this->iconPath = $this->path . DIRECTORY_SEPARATOR . ($yaml['icon'] ?? 'assets/icon.svg');
if (file_exists($this->iconPath)) {
$this->icon = file_get_contents($this->iconPath);
}
}
public function register(callable $callback)
{
$config = [
'name' => $this->name,
'title' => __($this->title),
'description' => __($this->description),
'render_callback' => function ($block, $content = '', $preview = false, $postId = 0, $wpBlock = null, $context = false) use ($callback) {
$callback($block, $preview, $context);
},
'category' => $this->category,
'keywords' => $this->keywords,
'class' => $this->name,
'path' => $this->path,
'mode' => 'edit',
'supports' => ['anchor' => true, 'align' => ['wide', 'full'], 'spacing' => ['margin' => ['top', 'bottom'], 'padding' => true], 'color' => ['text' => true, 'background' => true, 'gradients' => true]],
'icon' => $this->icon
];
acf_register_block_type($config);
}
public function override(string $namespace, string $newBasePath)
{
// Try to override the class
$classPath = $newBasePath . DIRECTORY_SEPARATOR . $this->name . DIRECTORY_SEPARATOR . $this->name . '.php';
if (file_exists($classPath)) {
$this->overridenClass = $namespace . '\\' . $this->name . '\\' . $this->name;
}
// Try to override the configuration
$configPath = $newBasePath . DIRECTORY_SEPARATOR . $this->name . DIRECTORY_SEPARATOR . 'block.yml';
if (file_exists($configPath)) {
$this->overrideConfiguration($namespace, Yaml::parseFile($configPath));
}
}
public function overrideConfiguration(string $namespace, array $yaml)
{
$this->overriden = true;
foreach ($yaml as $key => $value) {
$this->$key = $value;
}
}
public function getTemplate()
{
return '@' . $this->name . '/' . self::TEMPLATE_FILE_NAME;
}
}