| 1 |
<?php |
| 2 |
/** |
| 3 |
* OpenStation App Framework — view capture. |
| 4 |
* |
| 5 |
* A view is a callable that paints markup for a state: it may echo |
| 6 |
* (the natural thing inside `?> … <?php` blocks), return a string, or |
| 7 |
* both. `View::capture()` turns either into the HTML string the |
| 8 |
* runtime ships. |
| 9 |
* |
| 10 |
* @package OpenStation |
| 11 |
*/ |
| 12 |
|
| 13 |
namespace OpenStation\App; |
| 14 |
|
| 15 |
// Direct access, unless a standalone host is booting on bare PHP. |
| 16 |
if ( ! defined( 'ABSPATH' ) ) { |
| 17 |
defined( 'OPENSTATION_STANDALONE' ) || exit; |
| 18 |
} |
| 19 |
|
| 20 |
/** |
| 21 |
* Turns a view callable into HTML. |
| 22 |
*/ |
| 23 |
final class View { |
| 24 |
|
| 25 |
/** |
| 26 |
* Run a view callable and collect everything it painted. |
| 27 |
* |
| 28 |
* @param callable $view `function ( State $state, Os $os )`. |
| 29 |
* @param State $state Current state. |
| 30 |
* @param Os $os Host handle. |
| 31 |
* @return string HTML. |
| 32 |
* @throws \Throwable Whatever the view threw, after the output buffer is discarded. |
| 33 |
*/ |
| 34 |
public static function capture( callable $view, State $state, Os $os ) { |
| 35 |
ob_start(); |
| 36 |
try { |
| 37 |
$returned = $view( $state, $os ); |
| 38 |
} catch ( \Throwable $e ) { |
| 39 |
ob_end_clean(); |
| 40 |
throw $e; |
| 41 |
} |
| 42 |
$echoed = (string) ob_get_clean(); |
| 43 |
return $echoed . ( is_string( $returned ) ? $returned : '' ); |
| 44 |
} |
| 45 |
} |
| 46 |
|