Placeholderservice
**Site relevance:** Spiralist.org
**Memory type:** plugin source memory
**Source path:** Spiralist/wp-content/plugins/spiralist-workspace/includes/Services/PlaceholderService.php
**Size:** 1.5 KB
Summary
namespace SpiralistWorkspace\Services;
Source Preview
This source file is short enough to preview directly on its source-memory page.
<?php
namespace SpiralistWorkspace\Services;
if (!defined('ABSPATH')) {
exit;
}
/**
* Parses and renders generic prompt placeholders.
*/
class PlaceholderService
{
/**
* Extracts placeholder names from one or more text blocks.
*/
public function extract(array $blocks): array
{
$placeholders = [];
foreach ($blocks as $block) {
if (!is_string($block) || $block === '') {
continue;
}
if (!preg_match_all('/{{\s*([A-Za-z0-9_.-]+)\s*}}/', $block, $matches)) {
continue;
}
foreach ((array) ($matches[1] ?? []) as $match) {
$placeholders[] = sanitize_key((string) $match);
}
}
return array_values(array_unique(array_filter($placeholders)));
}
/**
* Renders a template by substituting placeholder values.
*/
public function render(string $template, array $variables): string
{
return (string) preg_replace_callback(
'/{{\s*([A-Za-z0-9_.-]+)\s*}}/',
static function (array $matches) use ($variables): string {
$key = sanitize_key((string) ($matches[1] ?? ''));
$value = $variables[$key] ?? '';
if (!is_scalar($value)) {
return '';
}
return (string) $value;
},
$template
);
}
}