| 1 |
<?php |
| 2 |
|
| 3 |
/* |
| 4 |
* This file is part of the WindPress package. |
| 5 |
* |
| 6 |
* (c) Joshua Gugun Siagian <suabahasa@gmail.com> |
| 7 |
* |
| 8 |
* For the full copyright and license information, please view the LICENSE |
| 9 |
* file that was distributed with this source code. |
| 10 |
*/ |
| 11 |
declare (strict_types=1); |
| 12 |
namespace WindPress\WindPress\Core\Scanner; |
| 13 |
|
| 14 |
use RuntimeException; |
| 15 |
use Throwable; |
| 16 |
use WP_Post; |
| 17 |
use WP_Query; |
| 18 |
class PostRenderer |
| 19 |
{ |
| 20 |
private const POST_GLOBALS = ['post', 'id', 'authordata', 'currentday', 'currentmonth', 'page', 'pages', 'multipage', 'more', 'numpages']; |
| 21 |
public static function render(WP_Post $post, array $renderers, string $provider, WP_Query $query): string |
| 22 |
{ |
| 23 |
if ($renderers === []) { |
| 24 |
return $post->post_content; |
| 25 |
} |
| 26 |
$previous_globals = []; |
| 27 |
foreach (self::POST_GLOBALS as $name) { |
| 28 |
if (array_key_exists($name, $GLOBALS)) { |
| 29 |
$previous_globals[$name] = $GLOBALS[$name]; |
| 30 |
} |
| 31 |
} |
| 32 |
$source_content = $post->post_content; |
| 33 |
$content = $source_content; |
| 34 |
try { |
| 35 |
$GLOBALS['post'] = $post; |
| 36 |
if (!$query->setup_postdata($post)) { |
| 37 |
throw new RuntimeException(__('Could not set up the post context.', 'windpress')); |
| 38 |
} |
| 39 |
foreach ($renderers as $renderer) { |
| 40 |
$content = $renderer($content); |
| 41 |
if (!is_string($content)) { |
| 42 |
throw new RuntimeException(__('The renderer must return a string.', 'windpress')); |
| 43 |
} |
| 44 |
} |
| 45 |
} catch (Throwable $throwable) { |
| 46 |
throw new RuntimeException(sprintf( |
| 47 |
/* translators: 1: Scan provider name, 2: Post ID, 3: Error message. */ |
| 48 |
__('%1$s could not render post #%2$d: %3$s', 'windpress'), |
| 49 |
$provider, |
| 50 |
$post->ID, |
| 51 |
$throwable->getMessage() |
| 52 |
), 0, $throwable); |
| 53 |
} finally { |
| 54 |
// REST requests have no main loop to restore with wp_reset_postdata(). |
| 55 |
foreach (self::POST_GLOBALS as $name) { |
| 56 |
if (array_key_exists($name, $previous_globals)) { |
| 57 |
$GLOBALS[$name] = $previous_globals[$name]; |
| 58 |
} else { |
| 59 |
unset($GLOBALS[$name]); |
| 60 |
} |
| 61 |
} |
| 62 |
} |
| 63 |
// Keep classes in conditional template branches that did not render. |
| 64 |
return $content === $source_content ? $content : $source_content . \PHP_EOL . $content; |
| 65 |
} |
| 66 |
} |
| 67 |
|