Skip to content

Commit 010294e

Browse files
committed
Improve type support and detection
1 parent cb8c9f9 commit 010294e

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

CHANGELOG.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,12 @@ All Notable changes to `bakame/http-strucured-fields` will be documented in this
66

77
### Added
88

9-
- None
9+
- Support for the `DisplayString` type
1010

1111
### Fixed
1212

1313
- Tests file moved under the `/tests` directory
14+
- Fix `Type::tryFromValue` to correctly detect string type derivative.
1415

1516
### Deprecated
1617

src/ByteSequence.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
use Stringable;
88

9+
use Throwable;
910
use function base64_decode;
1011
use function base64_encode;
1112
use function preg_match;
@@ -38,6 +39,15 @@ public static function fromEncoded(Stringable|string $encodedValue): self
3839
return new self($decoded);
3940
}
4041

42+
public static function tryFromEncoded(Stringable|string $encodedValue): ?self
43+
{
44+
try {
45+
return self::fromEncoded($encodedValue);
46+
} catch (Throwable) {
47+
return null;
48+
}
49+
}
50+
4151
/**
4252
* Returns a new instance from a raw decoded string.
4353
*/

src/Type.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
namespace Bakame\Http\StructuredFields;
66

77
use DateTimeInterface;
8+
use Throwable;
89

910
/**
1011
* @see https://www.rfc-editor.org/rfc/rfc8941.html#section-3.3
@@ -47,7 +48,12 @@ public static function tryFromValue(mixed $value): self|null
4748
is_int($value) => Type::Integer,
4849
is_float($value) => Type::Decimal,
4950
is_bool($value) => Type::Boolean,
50-
is_string($value) => 1 === preg_match('/[^\x20-\x7f]/', $value) ? Type::DisplayString : Type::String,
51+
is_string($value) => match (true) {
52+
1 === preg_match('/[^\x20-\x7f]/', $value) => Type::DisplayString,
53+
1 === preg_match("/^([a-z*][a-z\d:\/!#\$%&'*+\-.^_`|~]*)$/i", $value) => Type::Token,
54+
null !== ByteSequence::tryFromEncoded($value) => Type::ByteSequence,
55+
default => Type::String,
56+
},
5157
default => null,
5258
};
5359
}

0 commit comments

Comments
 (0)