| 1234567891011121314151617181920212223242526272829 |
- <?php
- namespace app\service;
- final class MqttTopic
- {
- public static function assertPublishable(string $topic): void
- {
- if ($topic === '' || strlen($topic) > 65535 || str_contains($topic, "\0") || strpbrk($topic, '+#') !== false) {
- throw new \InvalidArgumentException('MQTT topic is invalid.');
- }
- foreach (config('mqtt.publish_topics', []) as $filter) {
- if (self::matchesFilter($topic, $filter)) {
- return;
- }
- }
- throw new \InvalidArgumentException('MQTT topic is not permitted.');
- }
- private static function matchesFilter(string $topic, string $filter): bool
- {
- $pattern = preg_quote($filter, '/');
- $pattern = str_replace(['\\+', '\\#'], ['[^/]+', '.*'], $pattern);
- return (bool) preg_match('/^' . $pattern . '$/u', $topic);
- }
- }
|