| 1 |
<?php |
| 2 |
|
| 3 |
namespace Extendify\Notifications; |
| 4 |
|
| 5 |
defined('ABSPATH') || die('No direct access.'); |
| 6 |
|
| 7 |
/** |
| 8 |
* Availability is site state, so PHP decides it and JS is left with |
| 9 |
* dismissed/viewed. |
| 10 |
*/ |
| 11 |
class Availability |
| 12 |
{ |
| 13 |
public static function available(array $notifications) |
| 14 |
{ |
| 15 |
$candidates = array_filter($notifications, 'is_array'); |
| 16 |
$available = array_filter($candidates, [self::class, 'isAvailable']); |
| 17 |
usort($available, [self::class, 'byPriorityThenSlug']); |
| 18 |
return $available; |
| 19 |
} |
| 20 |
|
| 21 |
public static function anyIn(string $slot, array $notifications) |
| 22 |
{ |
| 23 |
foreach (self::available($notifications) as $notification) { |
| 24 |
if (in_array($slot, self::slotsOf($notification), true)) { |
| 25 |
return true; |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
return false; |
| 30 |
} |
| 31 |
|
| 32 |
private static function isAvailable(array $notification) |
| 33 |
{ |
| 34 |
return self::hasKnownSlot($notification) |
| 35 |
&& Triggers::passes($notification['trigger'] ?? null); |
| 36 |
} |
| 37 |
|
| 38 |
private static function hasKnownSlot(array $notification) |
| 39 |
{ |
| 40 |
foreach (self::slotsOf($notification) as $slot) { |
| 41 |
if (Slots::isKnown($slot)) { |
| 42 |
return true; |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
return false; |
| 47 |
} |
| 48 |
|
| 49 |
private static function slotsOf(array $notification) |
| 50 |
{ |
| 51 |
return array_values(array_filter( |
| 52 |
(array) ($notification['slots'] ?? []), |
| 53 |
'is_string' |
| 54 |
)); |
| 55 |
} |
| 56 |
|
| 57 |
private static function byPriorityThenSlug(array $a, array $b) |
| 58 |
{ |
| 59 |
$byPriority = ($b['priority'] ?? 0) <=> ($a['priority'] ?? 0); |
| 60 |
return $byPriority ?: strcmp($a['slug'] ?? '', $b['slug'] ?? ''); |
| 61 |
} |
| 62 |
} |
| 63 |
|