| 1 |
<?php |
| 2 |
/** |
| 3 |
* Handles all functionality for file expiration. |
| 4 |
* |
| 5 |
* @since 0.1.0 |
| 6 |
* |
| 7 |
* @package SolidWP\Performance |
| 8 |
*/ |
| 9 |
|
| 10 |
namespace SolidWP\Performance\Page_Cache; |
| 11 |
|
| 12 |
use InvalidArgumentException; |
| 13 |
|
| 14 |
if ( ! defined( 'ABSPATH' ) ) { |
| 15 |
exit; |
| 16 |
} |
| 17 |
|
| 18 |
/** |
| 19 |
* Page Cache file expiration. |
| 20 |
* |
| 21 |
* @since 0.1.0 |
| 22 |
* |
| 23 |
* @package SolidWP\Performance |
| 24 |
*/ |
| 25 |
class Expiration { |
| 26 |
|
| 27 |
/** |
| 28 |
* The default expiration length (1 Day in seconds). |
| 29 |
* |
| 30 |
* @since 0.1.0 |
| 31 |
* |
| 32 |
* @var int |
| 33 |
*/ |
| 34 |
private int $length; |
| 35 |
|
| 36 |
/** |
| 37 |
* The class constructor. |
| 38 |
* |
| 39 |
* @since 0.1.0 |
| 40 |
* |
| 41 |
* @param int $seconds The default expiration length (1 Day in seconds). |
| 42 |
* |
| 43 |
* @throws InvalidArgumentException If the length is less than or equal to 0. |
| 44 |
*/ |
| 45 |
public function __construct( int $seconds ) { |
| 46 |
if ( $seconds <= 0 ) { |
| 47 |
throw new InvalidArgumentException( 'The expiration $seconds must be greater than 0' ); |
| 48 |
} |
| 49 |
|
| 50 |
$this->length = $seconds; |
| 51 |
} |
| 52 |
|
| 53 |
/** |
| 54 |
* Determines if a file is older than the configured expiration. |
| 55 |
* |
| 56 |
* @since 0.1.0 |
| 57 |
* |
| 58 |
* @param string $file_path The full path to the file. |
| 59 |
* |
| 60 |
* @return bool |
| 61 |
*/ |
| 62 |
public function file_expired( string $file_path ): bool { |
| 63 |
$age = filemtime( $file_path ); |
| 64 |
$expiration = $age + $this->length; |
| 65 |
|
| 66 |
return time() > $expiration; |
| 67 |
} |
| 68 |
|
| 69 |
/** |
| 70 |
* Sets how long files are valid before they expire. |
| 71 |
* |
| 72 |
* @since 0.1.0 |
| 73 |
* |
| 74 |
* @param int $seconds Seconds files are valid before they expire. |
| 75 |
* |
| 76 |
* @throws InvalidArgumentException If the length is less than or equal to 0. |
| 77 |
* |
| 78 |
* @return void |
| 79 |
*/ |
| 80 |
public function set_expiration_length( int $seconds ): void { |
| 81 |
if ( $seconds <= 0 ) { |
| 82 |
throw new InvalidArgumentException( 'The expiration $seconds must be greater than 0' ); |
| 83 |
} |
| 84 |
|
| 85 |
$this->length = $seconds; |
| 86 |
} |
| 87 |
|
| 88 |
/** |
| 89 |
* Gets the number of seconds files should be kept before they expire. |
| 90 |
* |
| 91 |
* 0.1.0 |
| 92 |
* |
| 93 |
* @return int |
| 94 |
*/ |
| 95 |
public function get_expiration_length(): int { |
| 96 |
return $this->length; |
| 97 |
} |
| 98 |
} |
| 99 |
|