MqttTopic.php 868 B

1234567891011121314151617181920212223242526272829
  1. <?php
  2. namespace app\service;
  3. final class MqttTopic
  4. {
  5. public static function assertPublishable(string $topic): void
  6. {
  7. if ($topic === '' || strlen($topic) > 65535 || str_contains($topic, "\0") || strpbrk($topic, '+#') !== false) {
  8. throw new \InvalidArgumentException('MQTT topic is invalid.');
  9. }
  10. foreach (config('mqtt.publish_topics', []) as $filter) {
  11. if (self::matchesFilter($topic, $filter)) {
  12. return;
  13. }
  14. }
  15. throw new \InvalidArgumentException('MQTT topic is not permitted.');
  16. }
  17. private static function matchesFilter(string $topic, string $filter): bool
  18. {
  19. $pattern = preg_quote($filter, '/');
  20. $pattern = str_replace(['\\+', '\\#'], ['[^/]+', '.*'], $pattern);
  21. return (bool) preg_match('/^' . $pattern . '$/u', $topic);
  22. }
  23. }