| 1 |
<?php |
| 2 |
/** |
| 3 |
* A class to handle rendering notices in the admin. |
| 4 |
* |
| 5 |
* @since 0.1.0 |
| 6 |
* |
| 7 |
* @package SolidWP\Performance |
| 8 |
*/ |
| 9 |
|
| 10 |
declare( strict_types=1 ); |
| 11 |
|
| 12 |
namespace SolidWP\Performance\Notices; |
| 13 |
|
| 14 |
/** |
| 15 |
* A handler for rendering notices. |
| 16 |
* |
| 17 |
* @since 0.1.0 |
| 18 |
* |
| 19 |
* @package SolidWP\Performance |
| 20 |
*/ |
| 21 |
final class Notice_Handler { |
| 22 |
|
| 23 |
public const TRANSIENT = 'solid_performance_notices'; |
| 24 |
|
| 25 |
/** |
| 26 |
* An array of notices. |
| 27 |
* |
| 28 |
* @since 0.1.0 |
| 29 |
* |
| 30 |
* @var Notice[] |
| 31 |
*/ |
| 32 |
private array $notices; |
| 33 |
|
| 34 |
/** |
| 35 |
* The class constructor. |
| 36 |
*/ |
| 37 |
public function __construct() { |
| 38 |
$this->notices = $this->all(); |
| 39 |
} |
| 40 |
|
| 41 |
/** |
| 42 |
* Add a notice to display. |
| 43 |
* |
| 44 |
* @since 0.1.0 |
| 45 |
* |
| 46 |
* @param Notice $notice The notice to add. |
| 47 |
* |
| 48 |
* @return void |
| 49 |
*/ |
| 50 |
public function add( Notice $notice ): void { |
| 51 |
$this->notices = array_merge( $this->all(), [ $notice ] ); |
| 52 |
$this->save(); |
| 53 |
} |
| 54 |
|
| 55 |
/** |
| 56 |
* Display all notices and then clear them. |
| 57 |
* |
| 58 |
* @since 0.1.0 |
| 59 |
* |
| 60 |
* @action admin_notices |
| 61 |
* |
| 62 |
* @return void |
| 63 |
*/ |
| 64 |
public function display(): void { |
| 65 |
if ( count( $this->notices ) <= 0 ) { |
| 66 |
return; |
| 67 |
} |
| 68 |
|
| 69 |
foreach ( $this->notices as $notice ) { |
| 70 |
$args = $notice->to_array(); |
| 71 |
|
| 72 |
$classes = [ |
| 73 |
$args['alt'] ? 'notice-alt' : '', |
| 74 |
$args['large'] ? 'notice-large' : '', |
| 75 |
]; |
| 76 |
|
| 77 |
unset( $args['alt'] ); |
| 78 |
unset( $args['large'] ); |
| 79 |
|
| 80 |
// Remove any empty class values. |
| 81 |
$args['classes'] = array_filter( $classes ); |
| 82 |
|
| 83 |
wp_admin_notice( $args['message'], $args ); |
| 84 |
} |
| 85 |
|
| 86 |
$this->clear(); |
| 87 |
} |
| 88 |
|
| 89 |
/** |
| 90 |
* Clear all notices. |
| 91 |
* |
| 92 |
* @since 0.1.0 |
| 93 |
* |
| 94 |
* @return bool |
| 95 |
*/ |
| 96 |
public function clear(): bool { |
| 97 |
$this->notices = []; |
| 98 |
|
| 99 |
return (bool) delete_transient( self::TRANSIENT ); |
| 100 |
} |
| 101 |
|
| 102 |
/** |
| 103 |
* Get all notices. |
| 104 |
* |
| 105 |
* @since 0.1.0 |
| 106 |
* |
| 107 |
* @return Notice[] |
| 108 |
*/ |
| 109 |
private function all(): array { |
| 110 |
return array_filter( (array) get_transient( self::TRANSIENT ) ); |
| 111 |
} |
| 112 |
|
| 113 |
/** |
| 114 |
* Save the existing state of notices. |
| 115 |
* |
| 116 |
* @since 0.1.0 |
| 117 |
* |
| 118 |
* @return bool |
| 119 |
*/ |
| 120 |
private function save(): bool { |
| 121 |
return (bool) set_transient( self::TRANSIENT, $this->notices, 300 ); |
| 122 |
} |
| 123 |
} |
| 124 |
|