. */ namespace App\Services\LabelSystem; use App\Services\LabelSystem\PlaceholderProviders\PlaceholderProviderInterface; class LabelTextReplacer { protected $providers; public function __construct(iterable $providers) { $this->providers = $providers; } public function handlePlaceholder(string $placeholder, object $target): string { foreach ($this->providers as $provider) { /** @var PlaceholderProviderInterface $provider */ $ret = $provider->replace($placeholder, $target); if ($ret !== null) { return $ret; } } return $placeholder; } public function replace(string $lines, object $target): string { $patterns = [ '/(%%.*%%)/' => function ($match) use ($target) { return $this->handlePlaceholder($match[0], $target); }, ]; return preg_replace_callback_array($patterns, $lines); } }