| 1 |
<?php |
| 2 |
/** |
| 3 |
* The class responsible for collecting and storing fully rendered pages. |
| 4 |
* |
| 5 |
* @since 0.1.0 |
| 6 |
* |
| 7 |
* @package SolidWP\Performance |
| 8 |
*/ |
| 9 |
|
| 10 |
namespace SolidWP\Performance\Page_Cache; |
| 11 |
|
| 12 |
if ( ! defined( 'ABSPATH' ) ) { |
| 13 |
exit; |
| 14 |
} |
| 15 |
|
| 16 |
/** |
| 17 |
* A class for collecting and storing rendered pages. |
| 18 |
* |
| 19 |
* @since 0.1.0 |
| 20 |
* |
| 21 |
* @package SolidWP\Performance |
| 22 |
*/ |
| 23 |
class Buffer { |
| 24 |
|
| 25 |
/** |
| 26 |
* An instance of Cache. |
| 27 |
* |
| 28 |
* @since 0.1.0 |
| 29 |
* |
| 30 |
* @var Cache |
| 31 |
*/ |
| 32 |
private Cache $cache; |
| 33 |
|
| 34 |
/** |
| 35 |
* The class constructor. |
| 36 |
* |
| 37 |
* @since 0.1.0 |
| 38 |
* |
| 39 |
* @param Cache $cache An instance of Page_Cache\Cache. |
| 40 |
*/ |
| 41 |
public function __construct( Cache $cache ) { |
| 42 |
$this->cache = $cache; |
| 43 |
} |
| 44 |
|
| 45 |
/** |
| 46 |
* Registers the callback with Output Buffering. |
| 47 |
* |
| 48 |
* @since 0.1.0 |
| 49 |
* |
| 50 |
* @return void |
| 51 |
*/ |
| 52 |
public function register(): void { |
| 53 |
ob_start( [ $this, 'handle' ] ); |
| 54 |
} |
| 55 |
|
| 56 |
/** |
| 57 |
* The callback registered in the Output Buffer to save response. |
| 58 |
* |
| 59 |
* @since 0.1.0 |
| 60 |
* |
| 61 |
* @param string $buffer The output created for the request. |
| 62 |
* |
| 63 |
* @see https://www.php.net/manual/en/function.ob-start.php |
| 64 |
* |
| 65 |
* @return string |
| 66 |
*/ |
| 67 |
public function handle( string $buffer ): string { |
| 68 |
// This only fires on front-end requests. |
| 69 |
$count = did_action( 'template_redirect' ); |
| 70 |
|
| 71 |
if ( |
| 72 |
$count <= 0 || |
| 73 |
strlen( $buffer ) <= 0 |
| 74 |
) { |
| 75 |
return $buffer; |
| 76 |
} |
| 77 |
|
| 78 |
/** |
| 79 |
* Filter the HTML markup before rendering/saving it. |
| 80 |
* |
| 81 |
* @param string $html The HTML markup that will be written to cache. |
| 82 |
*/ |
| 83 |
$buffer = apply_filters( 'solidwp/performance/cache/html', $buffer ); |
| 84 |
|
| 85 |
$this->cache->save_output( $buffer ); |
| 86 |
|
| 87 |
return $buffer; |
| 88 |
} |
| 89 |
} |
| 90 |
|