give
/
vendor
/
vendor-prefixed
/
stellarwp
/
admin-notices
/
src
/
ValueObjects
/
ScreenCondition.php
NoticeLocation.php
1 year ago
NoticeUrgency.php
1 year ago
ScreenCondition.php
1 year ago
Script.php
1 year ago
Style.php
1 year ago
UserCapability.php
1 year ago
ScreenCondition.php
62 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Give\Vendors\StellarWP\AdminNotices\ValueObjects; |
| 4 | |
| 5 | use InvalidArgumentException; |
| 6 | |
| 7 | class ScreenCondition |
| 8 | { |
| 9 | /** |
| 10 | * @var string|array a string compared against the url, a regex for the url, or an array of conditions used against WP_Screen |
| 11 | * |
| 12 | * @see https://developer.wordpress.org/reference/classes/wp_screen/ |
| 13 | */ |
| 14 | private $condition; |
| 15 | |
| 16 | /** |
| 17 | * @var bool |
| 18 | */ |
| 19 | private $isRegex = true; |
| 20 | |
| 21 | public function __construct($condition) |
| 22 | { |
| 23 | $this->validateCondition($condition); |
| 24 | |
| 25 | $this->condition = $condition; |
| 26 | |
| 27 | // check if condition is a string with a regex using ~ as the delimiter |
| 28 | $this->isRegex = is_string($condition) && preg_match('/^~.+~[a-z]*$/', $condition) === 1; |
| 29 | } |
| 30 | |
| 31 | public function getCondition() |
| 32 | { |
| 33 | return $this->condition; |
| 34 | } |
| 35 | |
| 36 | public function isRegex(): bool |
| 37 | { |
| 38 | return $this->isRegex; |
| 39 | } |
| 40 | |
| 41 | private function validateCondition($condition) |
| 42 | { |
| 43 | // check if condition is a string or an array |
| 44 | if (!(is_string($condition) || is_array($condition))) { |
| 45 | throw new InvalidArgumentException('Screen condition must be a string or an array'); |
| 46 | } |
| 47 | |
| 48 | // check if array is an associative array with WP_Screen properties |
| 49 | static $wpScreenProperties = null; |
| 50 | |
| 51 | if ($wpScreenProperties === null) { |
| 52 | $wpScreenProperties = get_class_vars('WP_Screen'); |
| 53 | } |
| 54 | |
| 55 | if (is_array($condition) && array_diff_key($condition, $wpScreenProperties)) { |
| 56 | throw new InvalidArgumentException( |
| 57 | 'Screen condition must be an associative array with WP_Screen properties' |
| 58 | ); |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 |