| 1 |
<?php |
| 2 |
/** |
| 3 |
* Generic view renderer — loads a named template and executes it with a |
| 4 |
* `$data` array in scope. |
| 5 |
* |
| 6 |
* Usage: |
| 7 |
* $render->view( 'consent-screen', [ 'state' => $state ] ); |
| 8 |
*/ |
| 9 |
|
| 10 |
declare(strict_types=1); |
| 11 |
|
| 12 |
namespace WPMedia\MCP\OAuth\Views; |
| 13 |
|
| 14 |
/** |
| 15 |
* Render. |
| 16 |
* |
| 17 |
* Never uses `extract()` — templates read `$data['key']` directly. |
| 18 |
*/ |
| 19 |
class Render { |
| 20 |
|
| 21 |
/** |
| 22 |
* Directory templates are loaded from. |
| 23 |
* |
| 24 |
* @var string |
| 25 |
*/ |
| 26 |
private string $templates_dir; |
| 27 |
|
| 28 |
/** |
| 29 |
* Constructor. |
| 30 |
* |
| 31 |
* @param string|null $templates_dir Defaults to this class's own `templates/` directory. |
| 32 |
*/ |
| 33 |
public function __construct( ?string $templates_dir = null ) { |
| 34 |
$this->templates_dir = $templates_dir ?? __DIR__ . '/templates/'; |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* Render a named template, making `$data` available in its scope. |
| 39 |
* |
| 40 |
* Echoes directly (no internal `ob_start()`) so an exception thrown |
| 41 |
* mid-template doesn't leave a dangling output buffer behind. |
| 42 |
* |
| 43 |
* @param string $view Template name, without the `.php` extension. |
| 44 |
* @param array<string, mixed> $data Data made available to the template as `$data`. |
| 45 |
* @return void |
| 46 |
* |
| 47 |
* @throws \RuntimeException When the named template file does not exist. |
| 48 |
*/ |
| 49 |
public function view( string $view, array $data = [] ): void { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- $data is used via the required template's scope below. |
| 50 |
$path = $this->templates_dir . basename( $view ) . '.php'; |
| 51 |
|
| 52 |
if ( ! is_file( $path ) ) { |
| 53 |
throw new \RuntimeException( sprintf( 'View template not found: %s', $view ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- exception message, not HTML output; Render has no WordPress dependency. |
| 54 |
} |
| 55 |
|
| 56 |
require $path; |
| 57 |
} |
| 58 |
} |
| 59 |
|